<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/Frog_16px_1177822_easyicon.net.ico">
  <link rel="mask-icon" href="/images/Frog_32px_1177822_easyicon.net.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"hxy1997.xyz","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"输入关键字","hits_empty":"没有找到与「${query}」相关搜索","hits_stats":"${hits} 条相关记录，共耗时 ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="写惯了JavaScript，都忘了自己写的时候要注意数据的类型规范了，这种动态类型语言确实很灵活性有目共睹，但是也会导致各种奇怪的 bug。在Vue2.X版本，引入了 Flow 做静态类型检查，但微软的TypeScript 是更好的选择，毕竟大公司出品吗，一部分一部分的总结吧">
<meta property="og:type" content="article">
<meta property="og:title" content="Typescript速成自学">
<meta property="og:url" content="https://hxy1997.xyz/2021/04/07/Typescript%E9%80%9F%E6%88%90%E8%87%AA%E5%AD%A6/index.html">
<meta property="og:site_name" content="hxy的博客">
<meta property="og:description" content="写惯了JavaScript，都忘了自己写的时候要注意数据的类型规范了，这种动态类型语言确实很灵活性有目共睹，但是也会导致各种奇怪的 bug。在Vue2.X版本，引入了 Flow 做静态类型检查，但微软的TypeScript 是更好的选择，毕竟大公司出品吗，一部分一部分的总结吧">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418202745.png">
<meta property="article:published_time" content="2021-04-07T06:30:00.000Z">
<meta property="article:modified_time" content="2021-04-18T12:27:51.234Z">
<meta property="article:author" content="hxy">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="编程语言">
<meta property="article:tag" content="Typescript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418202745.png">

<link rel="canonical" href="https://hxy1997.xyz/2021/04/07/Typescript%E9%80%9F%E6%88%90%E8%87%AA%E5%AD%A6/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Typescript速成自学 | hxy的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="hxy的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">hxy的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Mia san Mia!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/huxingyi1997" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hxy1997.xyz/2021/04/07/Typescript%E9%80%9F%E6%88%90%E8%87%AA%E5%AD%A6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/Robben.gif">
      <meta itemprop="name" content="hxy">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hxy的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Typescript速成自学
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-04-07 14:30:00" itemprop="dateCreated datePublished" datetime="2021-04-07T14:30:00+08:00">2021-04-07</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-04-18 20:27:51" itemprop="dateModified" datetime="2021-04-18T20:27:51+08:00">2021-04-18</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">web前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">热度：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/04/07/Typescript%E9%80%9F%E6%88%90%E8%87%AA%E5%AD%A6/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/04/07/Typescript%E9%80%9F%E6%88%90%E8%87%AA%E5%AD%A6/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>写惯了JavaScript，都忘了自己写的时候要注意数据的类型规范了，这种动态类型语言确实很灵活性有目共睹，但是也会导致各种奇怪的 bug。在Vue2.X版本，引入了 Flow 做静态类型检查，但微软的TypeScript 是更好的选择，毕竟大公司出品吗，一部分一部分的总结吧</p>
<span id="more"></span>

<h1 id="1-初识-TypeScript"><a href="#1-初识-TypeScript" class="headerlink" title="1.初识 TypeScript"></a>1.初识 TypeScript</h1><p>TypeScript 是 JavaScript 语言的超集，为 JavaScript 添加了可选择的类型标注，大大增强了代码的可读性和可维护性。同时，它提供最新和不断发展的 JavaScript 特性，能让我们建立更丰富的组件。</p>
<h2 id="1-1-TypeScript-的特点"><a href="#1-1-TypeScript-的特点" class="headerlink" title="1.1 TypeScript 的特点"></a>1.1 TypeScript 的特点</h2><p>TypeScript 主要有 3 大特点：</p>
<ul>
<li><strong>始于JavaScript，归于JavaScript</strong></li>
</ul>
<p>TypeScript 可以编译出纯净、 简洁的 JavaScript 代码，并且可以运行在任何浏览器上、Node.js 环境中和任何支持 ECMAScript 3（或更高版本）的JavaScript 引擎中。</p>
<ul>
<li><strong>强大的工具构建大型应用程序</strong></li>
</ul>
<p>类型允许 JavaScript 开发者在开发 JavaScript 应用程序时使用高效的开发工具和常用操作比如静态检查和代码重构。</p>
<p>类型是可选的，类型推断让一些类型的注释使你的代码的静态验证有很大的不同。类型让你定义软件组件之间的接口和洞察现有 JavaScript 库的行为。</p>
<ul>
<li><strong>先进的 JavaScript</strong></li>
</ul>
<p>TypeScript 提供最新的和不断发展的 JavaScript 特性，包括那些来自 2015 年的 ECMAScript 和未来的提案中的特性，比如异步功能和 Decorators，以帮助建立健壮的组件。</p>
<p>这些特性为高可信应用程序开发时是可用的，但是会被编译成简洁的 ECMAScript3（或更新版本）的JavaScript。</p>
<p>下图显示了 TypeScript 与 ES5、ES2015 和 ES2016 之间的关系：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418202745.png" alt="img"></p>
<p><strong>TypeScript 与 JavaScript 的区别</strong></p>
<table>
<thead>
<tr>
<th>TypeScript</th>
<th>JavaScript</th>
</tr>
</thead>
<tbody><tr>
<td>JavaScript 的超集用于解决大型项目的代码复杂性</td>
<td>一种脚本语言，用于创建动态网页</td>
</tr>
<tr>
<td>可以在编译期间发现并纠正错误</td>
<td>作为一种解释型语言，只能在运行时发现错误</td>
</tr>
<tr>
<td>强类型，支持静态和动态类型</td>
<td>弱类型，没有静态类型选项</td>
</tr>
<tr>
<td>最终被编译成 JavaScript 代码，使浏览器可以理解</td>
<td>可以直接在浏览器中使用</td>
</tr>
<tr>
<td>支持模块、泛型和接口</td>
<td>不支持模块，泛型或接口</td>
</tr>
<tr>
<td>社区的支持仍在增长，而且还不是很大</td>
<td>大量的社区支持以及大量文档和解决问题的支持</td>
</tr>
</tbody></table>
<h2 id="1-2-安装-TypeScript"><a href="#1-2-安装-TypeScript" class="headerlink" title="1.2 安装 TypeScript"></a>1.2 安装 TypeScript</h2><p>命令行运行如下命令，全局安装 TypeScript：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install -g typescript</span><br></pre></td></tr></table></figure>

<p>安装完成后，在控制台运行如下命令，检查安装是否成功：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tsc -V </span><br></pre></td></tr></table></figure>

<p>结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Version 4.0.3</span><br></pre></td></tr></table></figure>

<h2 id="1-3-编写第一个-TypeScript-程序"><a href="#1-3-编写第一个-TypeScript-程序" class="headerlink" title="1.3 编写第一个 TypeScript 程序"></a>1.3 编写第一个 TypeScript 程序</h2><p>在编辑器，将下面的代码输入到 greeter.ts 文件里：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">greeter</span> (<span class="params">person</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;Hello, &#x27;</span> + person</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> user = <span class="string">&#x27;Yee&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(greeter(user))</span><br></pre></td></tr></table></figure>

<h3 id="1-3-1-编译代码"><a href="#1-3-1-编译代码" class="headerlink" title="1.3.1 编译代码"></a>1.3.1 编译代码</h3><p>我们使用了 <code>.ts</code> 扩展名，但是这段代码仅仅是 原生JavaScript 而已。</p>
<p>在命令行上，运行 TypeScript 编译器：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">tsc greeter.ts</span><br></pre></td></tr></table></figure>

<p>输出结果为一个 <code>greeter.js</code> 文件，它包含了和输入文件中相同的 JavsScript 代码。</p>
<p>在命令行上，通过 Node.js 运行这段代码：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">node greeter.js</span><br></pre></td></tr></table></figure>

<p>控制台输出：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Hello, Yee</span><br></pre></td></tr></table></figure>

<h3 id="1-3-2-类型注解"><a href="#1-3-2-类型注解" class="headerlink" title="1.3.2 类型注解"></a>1.3.2 类型注解</h3><p>接下来让我们看看 TypeScript 工具带来的高级功能。 给 <code>person</code> 函数的参数添加 <code>: string</code> 类型注解，如下：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">greeter</span> (<span class="params">person: <span class="built_in">string</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;Hello, &#x27;</span> + person</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> user = <span class="string">&#x27;Yee&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(greeter(user))</span><br></pre></td></tr></table></figure>

<p>TypeScript 里的类型注解是一种轻量级的为函数或变量添加约束的方式。 在这个例子里，我们希望 <code>greeter</code> 函数接收一个字符串参数。 然后尝试把 <code>greeter</code> 的调用改成传入一个数组：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">greeter</span> (<span class="params">person: <span class="built_in">string</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;Hello, &#x27;</span> + person</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> user = [<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>]</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(greeter(user))</span><br></pre></td></tr></table></figure>

<p>重新编译，你会看到产生了一个错误：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">error TS2345: Argument of type &#x27;number[]&#x27; is not assignable to parameter of type &#x27;string&#x27;.</span><br></pre></td></tr></table></figure>

<p>类似地，尝试删除 <code>greeter</code> 调用的所有参数。 TypeScript 会告诉你使用了非期望个数的参数调用了这个函数。 在这两种情况中，TypeScript提供了静态的代码分析，它可以分析代码结构和提供的类型注解。</p>
<p>要注意的是尽管有错误，<code>greeter.js</code> 文件还是被创建了。 就算你的代码里有错误，你仍然可以使用 TypeScript。但在这种情况下，TypeScript 会警告你代码可能不会按预期执行。</p>
<h3 id="1-3-3-接口"><a href="#1-3-3-接口" class="headerlink" title="1.3.3 接口"></a>1.3.3 接口</h3><p>让我们继续扩展这个示例应用。这里我们使用接口来描述一个拥有 <code>firstName</code> 和 <code>lastName</code> 字段的对象。 在 <code>TypeScript</code> 里，只在两个类型内部的结构兼容，那么这两个类型就是兼容的。 这就允许我们在实现接口时候只要保证包含了接口要求的结构就可以，而不必明确地使用 <code>implements</code> 语句。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Person &#123;</span><br><span class="line">    firstName: <span class="built_in">string</span></span><br><span class="line">    lastName: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">greeter</span> (<span class="params">person: Person</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;Hello, &#x27;</span> + person.firstName + <span class="string">&#x27; &#x27;</span> + person.lastName</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> user = &#123;</span><br><span class="line">  firstName: <span class="string">&#x27;Yee&#x27;</span>,</span><br><span class="line">  lastName: <span class="string">&#x27;Huang&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(greeter(user))</span><br></pre></td></tr></table></figure>

<h3 id="1-3-4-类"><a href="#1-3-4-类" class="headerlink" title="1.3.4 类"></a>1.3.4 类</h3><p>最后，让我们使用类来改写这个例子。 TypeScript 支持 JavaScript 的ES6新特性，比如支持基于类的面向对象编程。</p>
<p>让我们创建一个 <code>Student</code> 类，它带有一个构造函数和一些公共字段。因为类的字段包含了接口所需要的字段，所以他们能很好的兼容。</p>
<p>还要注意的是，我在类的声明上会注明所有的成员变量，这样比较一目了然。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">    fullName: <span class="built_in">string</span></span><br><span class="line">    firstName: <span class="built_in">string</span></span><br><span class="line">    lastName: <span class="built_in">string</span></span><br><span class="line"></span><br><span class="line">    <span class="title">constructor</span> (<span class="params">firstName: <span class="built_in">string</span>, lastName: <span class="built_in">string</span></span>) &#123;</span><br><span class="line">        <span class="built_in">this</span>.firstName = firstName</span><br><span class="line">        <span class="built_in">this</span>.lastName = lastName</span><br><span class="line">        <span class="built_in">this</span>.fullName = firstName + <span class="string">&#x27; &#x27;</span> + lastName</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> Person &#123;</span><br><span class="line">    firstName: <span class="built_in">string</span></span><br><span class="line">    lastName: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">greeter</span> (<span class="params">person: Person</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&#x27;Hello, &#x27;</span> + person.firstName + <span class="string">&#x27; &#x27;</span> + person.lastName</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> user = <span class="keyword">new</span> User(<span class="string">&#x27;Yee&#x27;</span>, <span class="string">&#x27;Huang&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(greeter(user))</span><br></pre></td></tr></table></figure>

<p>重新运行 <code>tsc greeter.ts</code>，你会看到 TypeScript 里的类只是一个语法糖，本质上还是 <code>JavaScript</code> 函数的实现。</p>
<h1 id="2-TypeScript基础类型"><a href="#2-TypeScript基础类型" class="headerlink" title="2.TypeScript基础类型"></a>2.TypeScript基础类型</h1><p>TypeScript 支持与 JavaScript 几乎相同的数据类型，此外还提供了实用的枚举类型方便我们使用。</p>
<h2 id="2-1-布尔值"><a href="#2-1-布尔值" class="headerlink" title="2.1 布尔值"></a>2.1 布尔值</h2><p>最基本的数据类型就是简单的 true/false 值，在JavaScript 和 TypeScript 里叫做 <code>boolean</code>。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> isDone: <span class="built_in">boolean</span> = <span class="literal">false</span></span><br></pre></td></tr></table></figure>

<h2 id="2-2-数字"><a href="#2-2-数字" class="headerlink" title="2.2 数字"></a>2.2 数字</h2><p>和 JavaScript 一样，TypeScript 里的所有数字都是浮点数。 这些浮点数的类型是 number。 除了支持十进制和十六进制字面量，TypeScript 还支持 ECMAScript 2015中引入的二进制和八进制字面量。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> decLiteral: <span class="built_in">number</span> = <span class="number">20</span></span><br><span class="line"><span class="keyword">let</span> hexLiteral: <span class="built_in">number</span> = <span class="number">0x14</span></span><br><span class="line"><span class="keyword">let</span> binaryLiteral: <span class="built_in">number</span> = <span class="number">0b10100</span></span><br><span class="line"><span class="keyword">let</span> octalLiteral: <span class="built_in">number</span> = <span class="number">0o24</span></span><br></pre></td></tr></table></figure>

<h2 id="2-3-字符串"><a href="#2-3-字符串" class="headerlink" title="2.3 字符串"></a>2.3 字符串</h2><p>TypeScript和 JavaScript 一样，可以使用双引号（<code>&quot;</code>）或单引号（<code>&#39;</code>）表示字符串。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> name: <span class="built_in">string</span> = <span class="string">&#x27;bob&#x27;</span></span><br><span class="line">name = <span class="string">&#x27;smith&#x27;</span></span><br></pre></td></tr></table></figure>

<p>你还可以使用模版字符串，它可以定义多行文本和内嵌表达式。 这种字符串是被反引号包围（ ```），并且以 <code>$&#123; expr &#125;</code> 这种形式嵌入表达式</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> name: <span class="built_in">string</span> = <span class="string">`Yee`</span></span><br><span class="line"><span class="keyword">let</span> age: <span class="built_in">number</span> = <span class="number">37</span></span><br><span class="line"><span class="keyword">let</span> sentence: <span class="built_in">string</span> = <span class="string">`Hello, my name is <span class="subst">$&#123; name &#125;</span>.</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">I&#x27;ll be <span class="subst">$&#123; age + <span class="number">1</span> &#125;</span> years old next month.`</span></span><br></pre></td></tr></table></figure>

<p>这与下面定义 <code>sentence</code> 的方式效果相同：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> sentence: <span class="built_in">string</span> = <span class="string">&#x27;Hello, my name is &#x27;</span> + name + <span class="string">&#x27;.\n\n&#x27;</span> +</span><br><span class="line">    <span class="string">&#x27;I\&#x27;ll be &#x27;</span> + (age + <span class="number">1</span>) + <span class="string">&#x27; years old next month.&#x27;</span></span><br></pre></td></tr></table></figure>

<h2 id="2-4-数组"><a href="#2-4-数组" class="headerlink" title="2.4 数组"></a>2.4 数组</h2><p>TypeScript 像 JavaScript 一样可以操作数组元素。 有两种方式可以定义数组。 第一种，可以在元素类型后面接上 <code>[]</code>，表示由此类型元素组成的一个数组：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> list: <span class="built_in">number</span>[] = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br></pre></td></tr></table></figure>

<p>第二种方式是使用数组泛型，<code>Array&lt;元素类型&gt;</code>：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> list: <span class="built_in">Array</span>&lt;<span class="built_in">number</span>&gt; = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br></pre></td></tr></table></figure>

<h2 id="2-5-元祖-Tuple"><a href="#2-5-元祖-Tuple" class="headerlink" title="2.5 元祖 Tuple"></a>2.5 元祖 Tuple</h2><p>元组类型允许表示一个已知元素数量和类型的数组，各元素的类型不必相同。 比如，你可以定义一对值分别为 <code>string</code> 和 <code>number</code> 类型的元组。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> x: [<span class="built_in">string</span>, <span class="built_in">number</span>]</span><br><span class="line">x = [<span class="string">&#x27;hello&#x27;</span>, <span class="number">10</span>] <span class="comment">// OK</span></span><br><span class="line">x = [<span class="number">10</span>, <span class="string">&#x27;hello&#x27;</span>] <span class="comment">// Error</span></span><br></pre></td></tr></table></figure>

<p>当访问一个已知索引的元素，会得到正确的类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(x[<span class="number">0</span>].substr(<span class="number">1</span>)) <span class="comment">// OK &#x27;ello&#x27;</span></span><br><span class="line"><span class="built_in">console</span>.log(x[<span class="number">1</span>].substr(<span class="number">1</span>)) <span class="comment">// Error, &#x27;number&#x27; 不存在 &#x27;substr&#x27; 方法</span></span><br></pre></td></tr></table></figure>

<p>当访问一个越界的元素，会使用联合类型替代：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">x[<span class="number">3</span>] = <span class="string">&#x27;world&#x27;</span> <span class="comment">// OK, 字符串可以赋值给(string | number)类型</span></span><br><span class="line"><span class="built_in">console</span>.log(x[<span class="number">5</span>].toString()) <span class="comment">// OK, &#x27;string&#x27; 和 &#x27;number&#x27; 都有 toString</span></span><br><span class="line">x[<span class="number">6</span>] = <span class="literal">true</span> <span class="comment">// Error, 布尔不是(string | number)类型</span></span><br></pre></td></tr></table></figure>

<h2 id="2-6-枚举"><a href="#2-6-枚举" class="headerlink" title="2.6 枚举"></a>2.6 枚举</h2><p><code>enum</code> 类型是对 JavaScript 标准数据类型的一个补充。 像 C# 等其它语言一样，使用枚举类型可以为一组数值赋予友好的名字。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">enum</span> Color &#123;Red, Green, Blue&#125;</span><br><span class="line"><span class="keyword">let</span> c: Color = Color.Green</span><br></pre></td></tr></table></figure>

<p>默认情况下，从 <code>0</code> 开始为元素编号。 你也可以手动的指定成员的数值。 例如，我们将上面的例子改成从 <code>1</code> 开始编号：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">enum</span> Color &#123;Red = <span class="number">1</span>, Green, Blue&#125;</span><br><span class="line"><span class="keyword">let</span> c: Color = Color.Green</span><br></pre></td></tr></table></figure>

<p>或者，全部都采用手动赋值：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">enum</span> Color &#123;Red = <span class="number">1</span>, Green = <span class="number">2</span>, Blue = <span class="number">4</span>&#125;</span><br><span class="line"><span class="keyword">let</span> c: Color = Color.Green</span><br></pre></td></tr></table></figure>

<p>枚举类型提供的一个便利是你可以由枚举的值得到它的名字。 例如，我们知道数值为 2，但是不确定它映射到 Color 里的哪个名字，我们可以查找相应的名字：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">enum</span> Color &#123;Red = <span class="number">1</span>, Green, Blue&#125;</span><br><span class="line"><span class="keyword">let</span> colorName: <span class="built_in">string</span> = Color[<span class="number">2</span>]</span><br><span class="line"><span class="built_in">console</span>.log(colorName)  <span class="comment">// 显示&#x27;Green&#x27;因为上面代码里它的值是2</span></span><br></pre></td></tr></table></figure>

<h2 id="2-7-any"><a href="#2-7-any" class="headerlink" title="2.7 any"></a>2.7 any</h2><p>有时候，我们会想要为那些在编程阶段还不清楚类型的变量指定一个类型。 这些值可能来自于动态的内容，比如来自用户输入或第三方代码库。 这种情况下，我们不希望类型检查器对这些值进行检查而是直接让它们通过编译阶段的检查。 那么我们可以使用 <code>any</code> 类型来标记这些变量：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> notSure: <span class="built_in">any</span> = <span class="number">4</span></span><br><span class="line">notSure = <span class="string">&#x27;maybe a string instead&#x27;</span></span><br><span class="line">notSure = <span class="literal">false</span> <span class="comment">// 也可以是个 boolean</span></span><br></pre></td></tr></table></figure>

<p>在对现有代码进行改写的时候，<code>any</code> 类型是十分有用的，它允许你在编译时可选择地包含或移除类型检查。并且当你只知道一部分数据的类型时，<code>any</code> 类型也是有用的。 比如，你有一个数组，它包含了不同的类型的数据：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> list: <span class="built_in">any</span>[] = [<span class="number">1</span>, <span class="literal">true</span>, <span class="string">&#x27;free&#x27;</span>]</span><br><span class="line"></span><br><span class="line">list[<span class="number">1</span>] = <span class="number">100</span></span><br></pre></td></tr></table></figure>

<h2 id="2-8-void"><a href="#2-8-void" class="headerlink" title="2.8 void"></a>2.8 void</h2><p>某种程度上来说，<code>void</code> 类型像是与 <code>any</code> 类型相反，它表示没有任何类型。 当一个函数没有返回值时，你通常会见到其返回值类型是 <code>void</code>：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">warnUser</span>(<span class="params"></span>): <span class="title">void</span> </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;This is my warning message&#x27;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>声明一个 <code>void</code> 类型的变量没有什么大用，因为你只能为它赋予 <code>undefined</code> 和 <code>null</code>：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> unusable: <span class="built_in">void</span> = <span class="literal">undefined</span></span><br></pre></td></tr></table></figure>

<h2 id="2-9-null-和-undefined"><a href="#2-9-null-和-undefined" class="headerlink" title="2.9 null 和 undefined"></a>2.9 null 和 undefined</h2><p>TypeScript 里，<code>undefined</code> 和 <code>null</code> 两者各自有自己的类型分别叫做 <code>undefined</code> 和 <code>null</code>。 和 <code>void</code> 相似，它们的本身的类型用处不是很大：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> u: <span class="literal">undefined</span> = <span class="literal">undefined</span></span><br><span class="line"><span class="keyword">let</span> n: <span class="literal">null</span> = <span class="literal">null</span></span><br></pre></td></tr></table></figure>

<p>默认情况下 <code>null</code> 和 <code>undefined</code> 是所有类型的子类型。 就是说你可以把 <code>null</code> 和 <code>undefined</code> 赋值给 <code>number</code> 类型的变量。</p>
<p>然而，当你指定了 <code>--strictNullChecks</code> 标记，<code>null</code> 和 <code>undefined</code> 只能赋值给 <code>void</code> 和它们各自，这能避免 很多常见的问题。 也许在某处你想传入一个 <code>string</code> 或 <code>null</code> 或 <code>undefined</code>，你可以使用联合类型 <code>string | null | undefined</code>。 再次说明，稍后我们会介绍联合类型。</p>
<h2 id="2-10-never"><a href="#2-10-never" class="headerlink" title="2.10 never"></a>2.10 never</h2><p><code>never</code> 类型表示的是那些永不存在的值的类型。 例如， <code>never</code> 类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型； 变量也可能是 <code>never</code> 类型，当它们被永不为真的类型保护所约束时。</p>
<p><code>never</code> 类型是任何类型的子类型，也可以赋值给任何类型；然而，没有类型是 <code>never</code> 的子类型或可以赋值给<code>never</code> 类型（除了 <code>never</code> 本身之外）。 即使 <code>any</code> 也不可以赋值给 <code>never</code>。</p>
<p>下面是一些返回 <code>never</code> 类型的函数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 返回never的函数必须存在无法达到的终点</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">error</span>(<span class="params">message: <span class="built_in">string</span></span>): <span class="title">never</span> </span>&#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(message)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 推断的返回值类型为never</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fail</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> error(<span class="string">&quot;Something failed&quot;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 返回never的函数必须存在无法达到的终点</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">infiniteLoop</span>(<span class="params"></span>): <span class="title">never</span> </span>&#123;</span><br><span class="line">    <span class="keyword">while</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-11-object"><a href="#2-11-object" class="headerlink" title="2.11 object"></a>2.11 object</h2><p><code>object</code> 表示非原始类型，也就是除 <code>number</code>，<code>string</code>，<code>boolean</code>，<code>symbol</code>，<code>null</code>或<code>undefined</code> 之外的类型。</p>
<p>使用 <code>object</code> 类型，就可以更好的表示像 <code>Object.create</code> 这样的 <code>API</code>。例如：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">declare</span> <span class="function"><span class="keyword">function</span> <span class="title">create</span>(<span class="params">o: <span class="built_in">object</span> | <span class="literal">null</span></span>): <span class="title">void</span></span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="title">create</span>(<span class="params">&#123; prop: <span class="number">0</span> &#125;</span>) // <span class="title">OK</span></span></span><br><span class="line"><span class="function"><span class="title">create</span>(<span class="params"><span class="literal">null</span></span>) // <span class="title">OK</span></span></span><br><span class="line"><span class="function"></span></span><br><span class="line"><span class="function"><span class="title">create</span>(<span class="params"><span class="number">42</span></span>) // <span class="title">Error</span></span></span><br><span class="line"><span class="function"><span class="title">create</span>(<span class="params"><span class="string">&#x27;string&#x27;</span></span>) // <span class="title">Error</span></span></span><br><span class="line"><span class="function"><span class="title">create</span>(<span class="params"><span class="literal">false</span></span>) // <span class="title">Error</span></span></span><br><span class="line"><span class="function"><span class="title">create</span>(<span class="params"><span class="literal">undefined</span></span>) // <span class="title">Error</span></span></span><br></pre></td></tr></table></figure>

<h2 id="2-12-类型断言"><a href="#2-12-类型断言" class="headerlink" title="2.12 类型断言"></a>2.12 类型断言</h2><p>通过类型断言这种方式可以告诉编译器，“相信我，我知道自己在干什么”。 类型断言好比其它语言里的类型转换，但是不进行特殊的数据检查和解构。 它没有运行时的影响，只是在编译阶段起作用。 TypeScript 会假设程序员已经进行了必须的检查。</p>
<p>类型断言有两种形式。 其一是“尖括号”语法：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> someValue: <span class="built_in">any</span> = <span class="string">&#x27;this is a string&#x27;</span></span><br><span class="line"><span class="keyword">let</span> strLength: <span class="built_in">number</span> = (&lt;<span class="built_in">string</span>&gt;someValue).length</span><br></pre></td></tr></table></figure>

<p>另一个为 <code>as</code> 语法：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> someValue: <span class="built_in">any</span> = <span class="string">&#x27;this is a string&#x27;</span></span><br><span class="line"><span class="keyword">let</span> strLength: <span class="built_in">number</span> = (someValue <span class="keyword">as</span> <span class="built_in">string</span>).length</span><br></pre></td></tr></table></figure>

<p>两种形式是等价的。 然而，当你在 TypeScript 里使用 JSX 时，只有 <code>as</code> 语法断言是被允许的。</p>
<h1 id="3-接口"><a href="#3-接口" class="headerlink" title="3.接口"></a>3.接口</h1><p>TypeScript 的核心原则之一是对值所具有的结构进行类型检查。它有时被称做“鸭式辨型法”或“结构性子类型化”。 在 TypeScript 里，接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。</p>
<h2 id="3-1-接口的定义"><a href="#3-1-接口的定义" class="headerlink" title="3.1 接口的定义"></a>3.1 接口的定义</h2><p>下面通过一个简单示例来观察接口是如何工作的：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printLabel</span>(<span class="params">labelledObj: &#123;</span></span></span><br><span class="line"><span class="function"><span class="params">    label: <span class="built_in">string</span></span></span></span><br><span class="line"><span class="function"><span class="params">&#125;</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(labelledObj.label)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myObj = &#123;</span><br><span class="line">    size: <span class="number">10</span>,</span><br><span class="line">    label: <span class="string">&#x27;Size 10 Object&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line">printLabel(myObj) <span class="comment">// &#x27;Size 10 Object&#x27;</span></span><br></pre></td></tr></table></figure>

<p>类型检查器会查看 <code>printLabel</code> 的调用。<code>printLabel</code> 有一个参数，并要求这个对象参数有一个名为 <code>label</code> 类型为 <code>string</code> 的属性。 需要注意的是，我们传入的对象参数实际上会包含很多属性，但是编译器只会检查那些必需的属性是否存在，以及其类型是否匹配。 然而，有些时候 TypeScript 却并不会这么宽松，我们下面会稍做讲解。</p>
<p>下面我们重写上面的例子，这次使用接口来描述：必须包含一个<code>label</code> 属性且类型为 <code>string</code>：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> LabelledValue &#123;</span><br><span class="line">    label: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printLabel</span>(<span class="params">labelledObj: LabelledValue</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(labelledObj.label)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myObj = &#123;</span><br><span class="line">    size: <span class="number">10</span>,</span><br><span class="line">    label: <span class="string">&#x27;Size 10 Object&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line">printLabel(myObj) <span class="comment">// &#x27;Size 10 Object&#x27;</span></span><br></pre></td></tr></table></figure>

<p><code>LabelledValue</code> 接口就好比一个名字，用来描述上面例子里的结构。 它代表了有一个 <code>label</code> 属性且类型为<code>string</code> 的对象。 需要注意的是，我们在这里并不能像在其它语言里一样，说传给 <code>printLabel</code> 的对象实现了这个接口。我们只会去关注值的外形。 只要传入的对象满足上面提到的必要条件，那么它就是被允许的。</p>
<p>还有一点值得提的是，类型检查器不会去检查属性的顺序，只要相应的属性存在并且类型也是对的就可以（就当对象理解好了）。</p>
<h2 id="3-2-可选属性"><a href="#3-2-可选属性" class="headerlink" title="3.2 可选属性"></a>3.2 可选属性</h2><p>接口里的属性不全都是必需的。 有些是只在某些条件下存在，或者根本不存在。例如给函数传入的参数对象中只有部分属性赋值了。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Square &#123;</span><br><span class="line">    color: <span class="built_in">string</span>,</span><br><span class="line"> 	area: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> SquareConfig &#123;</span><br><span class="line">    color?: <span class="built_in">string</span></span><br><span class="line">    width?: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createSquare</span> (<span class="params">config: SquareConfig</span>): <span class="title">Square</span> </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> newSquare = &#123;</span><br><span class="line">        color: <span class="string">&#x27;white&#x27;</span>,</span><br><span class="line">        area: <span class="number">100</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (config.color) &#123;</span><br><span class="line">        newSquare.color = config.color</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (config.width) &#123;</span><br><span class="line">        newSquare.area = config.width * config.width</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> newSquare</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> mySquare = createSquare(&#123;</span><br><span class="line">    color: <span class="string">&#x27;black&#x27;</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>带有可选属性的接口与普通的接口定义差不多，只是在可选属性名字定义的后面加一个 <code>?</code> 符号。</p>
<p>可选属性的好处之一是可以对可能存在的属性进行预定义，好处之二是可以捕获引用了不存在的属性时的错误。 比如，我们故意将 <code>createSquare</code> 里的 <code>color</code> 属性名拼错，就会得到一个错误提示：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Square &#123;</span><br><span class="line">    color: <span class="built_in">string</span>,</span><br><span class="line">	area: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> SquareConfig &#123;</span><br><span class="line">    color?: <span class="built_in">string</span>;</span><br><span class="line">    width?: <span class="built_in">number</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createSquare</span>(<span class="params">config: SquareConfig</span>): <span class="title">Square</span> </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> newSquare = &#123;</span><br><span class="line">        color: <span class="string">&#x27;white&#x27;</span>,</span><br><span class="line">        area: <span class="number">100</span></span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">if</span> (config.clor) &#123;</span><br><span class="line">        <span class="comment">// Error: 属性 &#x27;clor&#x27; 不存在于类型 &#x27;SquareConfig&#x27; 中</span></span><br><span class="line">        newSquare.color = config.clor;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (config.width) &#123;</span><br><span class="line">        newSquare.area = config.width * config.width;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> newSquare;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> mySquare = createSquare(&#123;</span><br><span class="line">    color: <span class="string">&#x27;black&#x27;</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="3-3-只读属性"><a href="#3-3-只读属性" class="headerlink" title="3.3 只读属性"></a>3.3 只读属性</h2><p>一些对象属性只能在对象刚刚创建的时候修改其值。 你可以在属性名前用 <code>readonly</code> 来指定只读属性:</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Point &#123;</span><br><span class="line">    <span class="keyword">readonly</span> x: <span class="built_in">number</span></span><br><span class="line">    <span class="keyword">readonly</span> y: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>你可以通过赋值一个对象字面量来构造一个 <code>Point</code>。 赋值后，<code>x</code> 和 <code>y</code> 再也不能被改变了。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> p1: Point = &#123;</span><br><span class="line">    x: <span class="number">10</span>,</span><br><span class="line">    y: <span class="number">20</span></span><br><span class="line">&#125;</span><br><span class="line">p1.x = <span class="number">5</span> <span class="comment">// error!</span></span><br></pre></td></tr></table></figure>

<p>TypeScript 具有 <code>ReadonlyArray&lt;T&gt;</code> 类型，它与 <code>Array&lt;T&gt;</code> 相似，只是把所有可变方法去掉了，因此可以确保数组创建后再也不能被修改：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a: <span class="built_in">number</span>[] = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line"><span class="keyword">let</span> ro: ReadonlyArray&lt;<span class="built_in">number</span>&gt; = a</span><br><span class="line">ro[<span class="number">0</span>] = <span class="number">12</span> <span class="comment">// error!</span></span><br><span class="line">ro.push(<span class="number">5</span>) <span class="comment">// error!</span></span><br><span class="line">ro.length = <span class="number">100</span> <span class="comment">// error!</span></span><br><span class="line">a = ro <span class="comment">// error!</span></span><br></pre></td></tr></table></figure>

<p>上面代码的最后一行，可以看到就算把整个 <code>ReadonlyArray</code> 赋值到一个普通数组也是不可以的。 但是你可以用类型断言重写：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a = ro <span class="keyword">as</span> <span class="built_in">number</span>[]</span><br></pre></td></tr></table></figure>

<h3 id="readonly-和-const区别"><a href="#readonly-和-const区别" class="headerlink" title="readonly 和 const区别"></a>readonly 和 const区别</h3><p>最简单判断该用 <code>readonly</code> 还是 <code>const</code> 的方法是看要把它做为变量使用还是做为一个属性。 做为变量使用的话用 <code>const</code>，若做为属性则使用 <code>readonly</code>。</p>
<h2 id="3-4-额外的属性检查"><a href="#3-4-额外的属性检查" class="headerlink" title="3.4 额外的属性检查"></a>3.4 额外的属性检查</h2><p>我们在第一个例子里使用了接口，TypeScript 让我们传入 <code>&#123; size: number; label: string; &#125;</code> 到仅期望得到 <code>&#123; label: string; &#125;</code> 的函数里, 并且我们已经学过了可选属性。</p>
<p>然而，天真地将这两者结合的话就会像在 JavaScript 里那样搬起石头砸自己的脚。 比如，拿 <code>createSquare</code> 例子来说：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> SquareConfig &#123;</span><br><span class="line">    color?: <span class="built_in">string</span>;</span><br><span class="line">    width?: <span class="built_in">number</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createSquare</span> (<span class="params">config: SquareConfig</span>): </span>&#123; color: <span class="built_in">string</span>; area: <span class="built_in">number</span> &#125; &#123;</span><br><span class="line">    <span class="keyword">let</span> newSquare = &#123;<span class="attr">color</span>: <span class="string">&#x27;white&#x27;</span>, <span class="attr">area</span>: <span class="number">100</span>&#125;</span><br><span class="line">    <span class="keyword">if</span> (config.color) &#123;</span><br><span class="line">        newSquare.color = config.color</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (config.width) &#123;</span><br><span class="line">        newSquare.area = config.width * config.width</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> newSquare</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> mySquare = createSquare(&#123;</span><br><span class="line">    colour: <span class="string">&#x27;red&#x27;</span>,</span><br><span class="line">    width: <span class="number">100</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// error TS2345: Argument of type &#x27;&#123; colour: string; width: number; &#125;&#x27; is not assignable to parameter of type &#x27;SquareConfig&#x27;.</span></span><br><span class="line"><span class="comment">//  Object literal may only specify known properties, but &#x27;colour&#x27; does not exist in type &#x27;SquareConfig&#x27;. Did you mean to write &#x27;color&#x27;?</span></span><br></pre></td></tr></table></figure>

<p>注意传入 <code>createSquare</code> 的参数拼写为 <code>colour</code> 而不是 <code>color</code>。 在 JavaScript 里，这会默默地失败。</p>
<p>你可能会争辩这个程序已经正确地类型化了，因为 <code>width</code> 属性是兼容的，不存在 <code>color</code> 属性，而且额外的 <code>colour</code> 属性是无意义的。</p>
<p>然而，TypeScript 会认为这段代码可能存在 bug。 对象字面量会被特殊对待而且会经过额外属性检查，当将它们赋值给变量或作为参数传递的时候。 如果一个对象字面量存在任何“目标类型”不包含的属性时，你会得到一个错误。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// error: &#x27;colour&#x27; 不存在于类型 &#x27;SquareConfig&#x27; 中</span></span><br><span class="line"><span class="keyword">let</span> mySquare = createSquare(&#123;</span><br><span class="line">    colour: <span class="string">&#x27;red&#x27;</span>,</span><br><span class="line">    width: <span class="number">100</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>绕开这些检查非常简单。 最简便的方法是使用类型断言：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> mySquare = createSquare(&#123; <span class="attr">width</span>: <span class="number">100</span>, <span class="attr">opacity</span>: <span class="number">0.5</span> &#125; <span class="keyword">as</span> SquareConfig)</span><br></pre></td></tr></table></figure>

<p>然而，最佳的方式是能够添加一个字符串索引签名，前提是你能够确定这个对象可能具有某些做为特殊用途使用的额外属性。 如果 <code>SquareConfig</code> 带有上面定义的类型的 <code>color</code> 和 <code>width</code> 属性，并且还会带有任意数量的其它属性，那么我们可以这样定义它：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> SquareConfig &#123;</span><br><span class="line">    color?: <span class="built_in">string</span></span><br><span class="line">    width?: <span class="built_in">number</span></span><br><span class="line">    [propName: <span class="built_in">string</span>]: <span class="built_in">any</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们稍后会讲到索引签名，但在这我们要表示的是<code>SquareConfig</code> 可以有任意数量的属性，并且只要它们不是 <code>color</code> 和 <code>width</code>，那么就无所谓它们的类型是什么。</p>
<p>还有最后一种跳过这些检查的方式，这可能会让你感到惊讶，它就是将这个对象赋值给一个另一个变量： 因为 <code>squareOptions</code> 不会经过额外属性检查，所以编译器不会报错。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> squareOptions = &#123;</span><br><span class="line">    colour: <span class="string">&#x27;red&#x27;</span>,</span><br><span class="line">    width: <span class="number">100</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> mySquare = createSquare(squareOptions)</span><br></pre></td></tr></table></figure>

<p>要留意，在像上面一样的简单代码里，你可能不应该去绕开这些检查。 对于包含方法和内部状态的复杂对象字面量来讲，你可能需要使用这些技巧，但是大多数额外属性检查错误是真正的bug。也就是说你遇到了额外类型检查出的错误，你应该去审查一下你的类型声明。 在这里，如果支持传入 <code>color</code> 或 <code>colour</code> 属性到 <code>createSquare</code>，你应该修改 <code>SquareConfig</code> 定义来体现出这一点。</p>
<h2 id="3-5-函数类型"><a href="#3-5-函数类型" class="headerlink" title="3.5 函数类型"></a>3.5 函数类型</h2><p>接口能够描述 JavaScript 中对象拥有的各种各样的外形。 除了描述带有属性的普通对象外，接口也可以描述函数类型。</p>
<p>为了使用接口表示函数类型，我们需要给接口定义一个调用签名。它就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> SearchFunc &#123;</span><br><span class="line">    (source: <span class="built_in">string</span>, <span class="attr">subString</span>: <span class="built_in">string</span>): <span class="built_in">boolean</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样定义后，我们可以像使用其它接口一样使用这个函数类型的接口。 下例展示了如何创建一个函数类型的变量，并将一个同类型的函数赋值给这个变量。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> mySearch: SearchFunc</span><br><span class="line">mySearch = <span class="function"><span class="keyword">function</span>(<span class="params">source: <span class="built_in">string</span>, subString: <span class="built_in">string</span></span>): <span class="title">boolean</span> </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> result = source.search(subString);</span><br><span class="line">    <span class="keyword">return</span> result &gt; -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>对于函数类型的类型检查来说，函数的参数名不需要与接口里定义的名字相匹配。 比如，我们使用下面的代码重写上面的例子：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> mySearch: SearchFunc</span><br><span class="line">mySearch = <span class="function"><span class="keyword">function</span>(<span class="params">src: <span class="built_in">string</span>, sub: <span class="built_in">string</span></span>): <span class="title">boolean</span> </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> result = src.search(sub);</span><br><span class="line">    <span class="keyword">return</span> result &gt; -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>函数的参数会逐个进行检查，要求对应位置上的参数类型是兼容的。 如果你不想指定类型，TypeScript 的类型系统会推断出参数类型，因为函数直接赋值给了 <code>SearchFunc</code> 类型变量。 函数的返回值类型是通过其返回值推断出来的（此例是 <code>false</code> 和 <code>true</code>）。 如果让这个函数返回数字或字符串，类型检查器会警告我们函数的返回值类型与 <code>SearchFunc</code> 接口中的定义不匹配。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> mySearch: SearchFunc</span><br><span class="line">mySearch = <span class="function"><span class="keyword">function</span>(<span class="params">src, sub</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> result = src.search(sub);</span><br><span class="line">    <span class="keyword">return</span> result &gt; -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="3-6-可索引的类型"><a href="#3-6-可索引的类型" class="headerlink" title="3.6 可索引的类型"></a>3.6 可索引的类型</h2><p>与使用接口描述函数类型差不多，我们也可以描述那些能够“通过索引得到”的类型，比如 <code>a[10]</code> 或 <code>ageMap[&#39;daniel&#39;]</code>。 可索引类型具有一个 索引签名，它描述了对象索引的类型，还有相应的索引返回值类型。 让我们看一个例子：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> StringArray &#123;</span><br><span class="line">    [index: <span class="built_in">number</span>]: <span class="built_in">string</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myArray: StringArray;</span><br><span class="line">myArray = [<span class="string">&#x27;Bob&#x27;</span>, <span class="string">&#x27;Fred&#x27;</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myStr: <span class="built_in">string</span> = myArray[<span class="number">0</span>]; <span class="comment">// &#x27;Bob&#x27;</span></span><br></pre></td></tr></table></figure>

<p>上面例子里，我们定义了 <code>StringArray</code> 接口，它具有索引签名。 这个索引签名表示了当用 <code>number</code> 去索引 <code>StringArray</code> 时会得到 <code>string</code> 类型的返回值。</p>
<p>TypeScript 支持两种索引签名：字符串和数字。 可以同时使用两种类型的索引，但是数字索引的返回值必须是字符串索引返回值类型的子类型。 这是因为当使用 <code>number</code> 来索引时，JavaScript 会将它转换成<code>string</code> 然后再去索引对象。 也就是说用 <code>100</code>（一个 <code>number</code>）去索引等同于使用<code>&#39;100&#39;</code>（一个 <code>string</code> ）去索引，因此两者需要保持一致。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    name: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dog</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    breed: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 错误：使用数值型的字符串索引，有时会得到完全不同的Animal!</span></span><br><span class="line"><span class="keyword">interface</span> NotOkay &#123;</span><br><span class="line">    [x: <span class="built_in">number</span>]: Animal</span><br><span class="line">    [x: <span class="built_in">string</span>]: Dog</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>字符串索引签名能够很好的描述 <code>dictionary</code> 模式，并且它们也会确保所有属性与其返回值类型相匹配。 因为字符串索引声明了 <code>obj.property</code> 和 <code>obj[&#39;property&#39;]</code> 两种形式都可以。 下面的例子里， <code>name</code> 的类型与字符串索引类型不匹配，所以类型检查器给出一个错误提示：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> NumberDictionary &#123;</span><br><span class="line">    [index: <span class="built_in">string</span>]: <span class="built_in">number</span>;</span><br><span class="line">    length: <span class="built_in">number</span>;    <span class="comment">// 可以，length是number类型</span></span><br><span class="line">    name: <span class="built_in">string</span>       <span class="comment">// 错误，`name`的类型与索引类型返回值的类型不匹配</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最后，你可以将索引签名设置为只读，这样就防止了给索引赋值：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> ReadonlyStringArray &#123;</span><br><span class="line">    <span class="keyword">readonly</span> [index: <span class="built_in">number</span>]: <span class="built_in">string</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> myArray: ReadonlyStringArray = [<span class="string">&#x27;Alice&#x27;</span>, <span class="string">&#x27;Bob&#x27;</span>];</span><br><span class="line">myArray[<span class="number">2</span>] = <span class="string">&#x27;Mallory&#x27;</span>; <span class="comment">// error!</span></span><br></pre></td></tr></table></figure>

<h2 id="3-7-类类型"><a href="#3-7-类类型" class="headerlink" title="3.7 类类型"></a>3.7 类类型</h2><h3 id="3-7-1-实现接口"><a href="#3-7-1-实现接口" class="headerlink" title="3.7.1 实现接口"></a>3.7.1 实现接口</h3><p>与 C# 或 Java 里接口的基本作用一样，TypeScript 也能够用它来明确的强制一个类去符合某种契约。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> ClockInterface &#123;</span><br><span class="line">    currentTime: <span class="built_in">Date</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Clock</span> <span class="title">implements</span> <span class="title">ClockInterface</span> </span>&#123;</span><br><span class="line">    currentTime: <span class="built_in">Date</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">h: <span class="built_in">number</span>, m: <span class="built_in">number</span></span>)</span> &#123; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>你也可以在接口中描述一个方法，在类里实现它，如同下面的 <code>setTime</code> 方法一样：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> ClockInterface &#123;</span><br><span class="line">    currentTime: <span class="built_in">Date</span></span><br><span class="line">    setTime(d: <span class="built_in">Date</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Clock</span> <span class="title">implements</span> <span class="title">ClockInterface</span> </span>&#123;</span><br><span class="line">    currentTime: <span class="built_in">Date</span></span><br><span class="line">    <span class="function"><span class="title">setTime</span>(<span class="params">d: <span class="built_in">Date</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.currentTime = d</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">h: <span class="built_in">number</span>, m: <span class="built_in">number</span></span>)</span> &#123;</span><br><span class="line">    </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接口描述了类的公共部分，而不是公共和私有两部分。 它不会帮你检查类是否具有某些私有成员。</p>
<h3 id="3-7-2-类静态部分与实例部分的区别"><a href="#3-7-2-类静态部分与实例部分的区别" class="headerlink" title="3.7.2 类静态部分与实例部分的区别"></a>3.7.2 类静态部分与实例部分的区别</h3><p>当你操作类和接口的时候，你要知道类是具有两个类型的：静态部分的类型和实例的类型。 你会注意到，当你用构造器签名去定义一个接口并试图定义一个类去实现这个接口时会得到一个错误：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> ClockConstructor &#123;</span><br><span class="line">    <span class="keyword">new</span> (hour: <span class="built_in">number</span>, <span class="attr">minute</span>: <span class="built_in">number</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// error</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Clock</span> <span class="title">implements</span> <span class="title">ClockConstructor</span> </span>&#123;</span><br><span class="line">    currentTime: <span class="built_in">Date</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">h: <span class="built_in">number</span>, m: <span class="built_in">number</span></span>)</span> &#123; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里因为当一个类实现了一个接口时，只对其实例部分进行类型检查。<code>constructor</code> 存在于类的静态部分，所以不在检查的范围内。</p>
<p>看下面的例子，我们定义了两个接口， <code>ClockConstructor</code> 为构造函数所用和 <code>ClockInterface</code> 为实例方法所用。 为了方便我们定义一个构造函数 <code>createClock</code>，它用传入的类型创建实例。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> ClockConstructor &#123;</span><br><span class="line">    <span class="keyword">new</span> (hour: <span class="built_in">number</span>, <span class="attr">minute</span>: <span class="built_in">number</span>): ClockInterface</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">interface</span> ClockInterface &#123;</span><br><span class="line">    tick()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createClock</span>(<span class="params">ctor: ClockConstructor, hour: <span class="built_in">number</span>, minute: <span class="built_in">number</span></span>): <span class="title">ClockInterface</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> ctor(hour, minute)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DigitalClock</span> <span class="title">implements</span> <span class="title">ClockInterface</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">h: <span class="built_in">number</span>, m: <span class="built_in">number</span></span>)</span> &#123; &#125;</span><br><span class="line">    <span class="function"><span class="title">tick</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;beep beep&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AnalogClock</span> <span class="title">implements</span> <span class="title">ClockInterface</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">h: <span class="built_in">number</span>, m: <span class="built_in">number</span></span>)</span> &#123; &#125;</span><br><span class="line">    <span class="function"><span class="title">tick</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;tick tock&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> digital = createClock(DigitalClock, <span class="number">12</span>, <span class="number">17</span>)</span><br><span class="line"><span class="keyword">let</span> analog = createClock(AnalogClock, <span class="number">7</span>, <span class="number">32</span>)</span><br></pre></td></tr></table></figure>

<p>因为 <code>createClock</code> 的第一个参数是 <code>ClockConstructor</code> 类型，在 <code>createClock(AnalogClock, 7, 32)</code> 里，会检查 <code>AnalogClock</code> 是否符合构造函数签名。</p>
<h2 id="3-8-继承接口"><a href="#3-8-继承接口" class="headerlink" title="3.8 继承接口"></a>3.8 继承接口</h2><p>和类一样，接口也可以相互继承。 这让我们能够从一个接口里复制成员到另一个接口里，可以更灵活地将接口分割到可重用的模块里。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Shape &#123;</span><br><span class="line">    color: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> Square <span class="keyword">extends</span> Shape &#123;</span><br><span class="line">    sideLength: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> square = &#123;&#125; <span class="keyword">as</span> Square</span><br><span class="line">square.color = <span class="string">&#x27;blue&#x27;</span></span><br><span class="line">square.sideLength = <span class="number">10</span></span><br></pre></td></tr></table></figure>

<p>一个接口可以继承多个接口，创建出多个接口的合成接口。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Shape &#123;</span><br><span class="line">    color: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> PenStroke &#123;</span><br><span class="line">    penWidth: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> Square <span class="keyword">extends</span> Shape, PenStroke &#123;</span><br><span class="line">    sideLength: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> square = &#123;&#125; <span class="keyword">as</span> Square</span><br><span class="line">square.color = <span class="string">&#x27;blue&#x27;</span></span><br><span class="line">square.sideLength = <span class="number">10</span></span><br><span class="line">square.penWidth = <span class="number">5.0</span></span><br></pre></td></tr></table></figure>

<h2 id="3-9-混合类型"><a href="#3-9-混合类型" class="headerlink" title="3.9 混合类型"></a>3.9 混合类型</h2><p>先前我们提过，接口能够描述 JavaScript 里丰富的类型。 因为 JavaScript 其动态灵活的特点，有时你会希望一个对象可以同时具有上面提到的多种类型。</p>
<p>一个例子就是，一个对象可以同时做为函数和对象使用，并带有额外的属性。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Counter &#123;</span><br><span class="line">    (start: <span class="built_in">number</span>): <span class="built_in">string</span></span><br><span class="line">    interval: <span class="built_in">number</span></span><br><span class="line">    reset(): <span class="built_in">void</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getCounter</span>(<span class="params"></span>): <span class="title">Counter</span> </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> counter = (<span class="function"><span class="keyword">function</span> (<span class="params">start: <span class="built_in">number</span></span>) </span>&#123; &#125;) <span class="keyword">as</span> Counter</span><br><span class="line">    counter.interval = <span class="number">123</span></span><br><span class="line">    counter.reset = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123; &#125;</span><br><span class="line">    <span class="keyword">return</span> counter</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> c = getCounter()</span><br><span class="line">c(<span class="number">10</span>)</span><br><span class="line">c.reset()</span><br><span class="line">c.interval = <span class="number">5.0</span></span><br></pre></td></tr></table></figure>

<p>在使用 JavaScript 第三方库的时候，你可能需要像上面那样去完整地定义类型。</p>
<h2 id="3-10-接口继承类"><a href="#3-10-接口继承类" class="headerlink" title="3.10 接口继承类"></a>3.10 接口继承类</h2><p>当接口继承了一个类类型时，它会继承类的成员但不包括其实现。 就好像接口声明了所有类中存在的成员，但并没有提供具体实现一样。 接口同样会继承到类的 <code>private</code> 和 <code>protected</code> 成员。 这意味着当你创建了一个接口继承了一个拥有私有或受保护的成员的类时，这个接口类型只能被这个类或其子类所实现（implement）。</p>
<p>当你有一个庞大的继承结构时这很有用，但要指出的是你的代码只在子类拥有特定属性时起作用。 这个子类除了继承至基类外与基类没有任何关系。例：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Control</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> state: <span class="built_in">any</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> SelectableControl <span class="keyword">extends</span> Control &#123;</span><br><span class="line">    select(): <span class="built_in">void</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Button</span> <span class="keyword">extends</span> <span class="title">Control</span> <span class="title">implements</span> <span class="title">SelectableControl</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">select</span>(<span class="params"></span>)</span> &#123; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">TextBox</span> <span class="keyword">extends</span> <span class="title">Control</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">select</span>(<span class="params"></span>)</span> &#123; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Error：“ImageC”类型缺少“state”属性。</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ImageC</span> <span class="title">implements</span> <span class="title">SelectableControl</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">select</span>(<span class="params"></span>)</span> &#123; &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上面的例子里，<code>SelectableControl</code> 包含了 <code>Control</code> 的所有成员，包括私有成员 <code>state</code>。 因为 <code>state</code> 是私有成员，所以只能够是 <code>Control</code> 的子类们才能实现 <code>SelectableControl</code> 接口。 因为只有 <code>Control</code> 的子类才能够拥有一个声明于<code>Control</code> 的私有成员 <code>state</code>，这对私有成员的兼容性是必需的。</p>
<p>在 <code>Control</code> 类内部，是允许通过 <code>SelectableControl</code> 的实例来访问私有成员 <code>state</code> 的。 实际上，<code>SelectableControl</code> 接口和拥有 <code>select</code> 方法的 <code>Control</code> 类是一样的。<code>Button</code>和 <code>TextBox</code> 类是 <code>SelectableControl</code> 的子类（因为它们都继承自<code>Control</code> 并有 <code>select</code> 方法），但 <code>ImageC</code> 类并不是这样的。</p>
<h1 id="4-类"><a href="#4-类" class="headerlink" title="4.类"></a>4.类</h1><p>对于传统的 JavaScript 程序我们会使用函数和基于原型的继承来创建可重用的组件，但对于熟悉使用面向对象方式的程序员使用这些语法就有些棘手，因为他们用的是基于类的继承并且对象是由类构建出来的。 从 ECMAScript 2015，也就是 ES6 开始， JavaScript 程序员将能够使用基于类的面向对象的方式。 使用 TypeScript，我们允许开发者现在就使用这些特性，并且编译后的 JavaScript 可以在所有主流浏览器和平台上运行，而不需要等到下个 JavaScript 版本。</p>
<h2 id="4-1-类的基本示例"><a href="#4-1-类的基本示例" class="headerlink" title="4.1 类的基本示例"></a>4.1 类的基本示例</h2><p>下面看一个使用类的例子：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Greeter</span> </span>&#123;</span><br><span class="line">    greeting: <span class="built_in">string</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">message: <span class="built_in">string</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.greeting = message</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">greet</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;Hello, &#x27;</span> + <span class="built_in">this</span>.greeting</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> greeter = <span class="keyword">new</span> Greeter(<span class="string">&#x27;world&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>如果你使用过 C# 或 Java，你会对这种语法非常熟悉。 我们声明一个 <code>Greeter</code> 类。这个类有 3 个成员：一个叫做 <code>greeting</code> 的属性，一个构造函数和一个 <code>greet</code> 方法。</p>
<p>你会注意到，我们在引用任何一个类成员的时候都用了 <code>this</code>。 它表示我们访问的是类的成员。</p>
<p>最后一行，我们使用 <code>new</code> 构造了 <code>Greeter</code> 类的一个实例。它会调用之前定义的构造函数，创建一个 <code>Greeter</code> 类型的新对象，并执行构造函数初始化它。</p>
<h2 id="4-2-继承"><a href="#4-2-继承" class="headerlink" title="4.2 继承"></a>4.2 继承</h2><p>在 TypeScript 里，我们可以使用常用的面向对象模式。 基于类的程序设计中一种最基本的模式是允许使用继承来扩展现有的类。</p>
<p>看下面的例子：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">move</span>(<span class="params">distance: <span class="built_in">number</span> = <span class="number">0</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`Animal moved <span class="subst">$&#123;distance&#125;</span>m.`</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dog</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">bark</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Woof! Woof!&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> dog = <span class="keyword">new</span> Dog()</span><br><span class="line">dog.bark()</span><br><span class="line">dog.move(<span class="number">10</span>)</span><br></pre></td></tr></table></figure>

<p>这个例子展示了最基本的继承：类从基类中继承了属性和方法。 这里，<code>Dog</code> 是一个 派生类，它派生自 <code>Animal</code> 基类，通过 <code>extends</code> 关键字。 派生类通常被称作<em>子类</em>，基类通常被称作<em>超类</em>。</p>
<p>因为 <code>Dog</code> 继承了 <code>Animal</code> 的功能，因此我们可以创建一个 <code>Dog</code> 的实例，它能够 <code>bark()</code> 和 <code>move()</code>。</p>
<p>下面我们来看个更加复杂的例子。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    name: <span class="built_in">string</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123; </span><br><span class="line">        <span class="built_in">this</span>.name = name</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">move</span>(<span class="params">distance: <span class="built_in">number</span> = <span class="number">0</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;<span class="built_in">this</span>.name&#125;</span> moved <span class="subst">$&#123;distance&#125;</span>m.`</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Snake</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123; </span><br><span class="line">        <span class="built_in">super</span>(name)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">move</span>(<span class="params">distance: <span class="built_in">number</span> = <span class="number">5</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Slithering...&#x27;</span>)</span><br><span class="line">        <span class="built_in">super</span>.move(distance)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Horse</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(name)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">move</span>(<span class="params">distance: <span class="built_in">number</span> = <span class="number">45</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Galloping...&#x27;</span>)</span><br><span class="line">        <span class="built_in">super</span>.move(distance)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> sam = <span class="keyword">new</span> Snake(<span class="string">&#x27;Sammy&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> tom: Animal = <span class="keyword">new</span> Horse(<span class="string">&#x27;Tommy&#x27;</span>)</span><br><span class="line"></span><br><span class="line">sam.move()</span><br><span class="line">tom.move(<span class="number">34</span>)</span><br></pre></td></tr></table></figure>

<p>这个例子展示了一些上面没有提到的特性。 这一次，我们使用 <code>extends</code> 关键字创建了 Animal的两个子类：<code>Horse</code> 和 <code>Snake</code>。</p>
<p>与前一个例子的不同点是，派生类包含了一个构造函数，它 必须调用 <code>super()</code>，它会执行基类的构造函数。 而且，在构造函数里访问 <code>this</code> 的属性之前，我们 一定要调用 <code>super()</code>。 这个是 TypeScript 强制执行的一条重要规则。</p>
<p>这个例子演示了如何在子类里可以重写父类的方法。<code>Snake</code>类和 <code>Horse</code> 类都创建了 <code>move</code> 方法，它们重写了从 <code>Animal</code> 继承来的 <code>move</code> 方法，使得 <code>move</code> 方法根据不同的类而具有不同的功能。注意，即使 <code>tom</code> 被声明为 <code>Animal</code> 类型，但因为它的值是 <code>Horse</code>，调用 <code>tom.move(34)</code> 时，它会调用 <code>Horse</code> 里重写的方法。</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Slithering...</span><br><span class="line">Sammy moved 5m.</span><br><span class="line">Galloping...</span><br><span class="line">Tommy moved 34m.</span><br></pre></td></tr></table></figure>

<h2 id="4-3-公共，私有与受保护的修饰符"><a href="#4-3-公共，私有与受保护的修饰符" class="headerlink" title="4.3 公共，私有与受保护的修饰符"></a>4.3 公共，私有与受保护的修饰符</h2><h3 id="4-3-1-默认public"><a href="#4-3-1-默认public" class="headerlink" title="4.3.1 默认public"></a>4.3.1 默认public</h3><p>在上面的例子里，我们可以自由的访问程序里定义的成员。 如果你对其它语言中的类比较了解，就会注意到我们在之前的代码里并没有使用 <code>public</code> 来做修饰；例如，C# 要求必须明确地使用 <code>public</code> 指定成员是可见的。 在 TypeScript 里，成员都默认为 <code>public</code>。</p>
<p>你也可以明确的将一个成员标记成 <code>public</code>。 我们可以用下面的方式来重写上面的 <code>Animal</code> 类：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> name: <span class="built_in">string</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="title">move</span>(<span class="params">distance: <span class="built_in">number</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">`<span class="subst">$&#123;<span class="built_in">this</span>.name&#125;</span> moved <span class="subst">$&#123;distance&#125;</span>m.`</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="4-3-2-理解-private"><a href="#4-3-2-理解-private" class="headerlink" title="4.3.2 理解 private"></a>4.3.2 理解 private</h3><p>当成员被标记成 <code>private</code> 时，它就不能在声明它的类的外部访问。比如：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> name: <span class="built_in">string</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123; </span><br><span class="line">        <span class="built_in">this</span>.name = name</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> Animal(<span class="string">&#x27;Cat&#x27;</span>).name <span class="comment">// 错误: &#x27;name&#x27; 是私有的.</span></span><br></pre></td></tr></table></figure>

<p>TypeScript 使用的是结构性类型系统。 当我们比较两种不同的类型时，并不在乎它们从何处而来，如果所有成员的类型都是兼容的，我们就认为它们的类型是兼容的。</p>
<p>然而，当我们比较带有 <code>private</code> 或 <code>protected</code> 成员的类型的时候，情况就不同了。 如果其中一个类型里包含一个 <code>private</code> 成员，那么只有当另外一个类型中也存在这样一个 <code>private</code> 成员，并且它们都是来自同一处声明时，我们才认为这两个类型是兼容的。 对于 <code>protected</code> 成员也使用这个规则。</p>
<p>下面来看一个例子，更好地说明了这一点：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> name: <span class="built_in">string</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123; </span><br><span class="line">        <span class="built_in">this</span>.name = name </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Rhino</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123; </span><br><span class="line">        <span class="built_in">super</span>(<span class="string">&#x27;Rhino&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Employee</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> name: <span class="built_in">string</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123; </span><br><span class="line">        <span class="built_in">this</span>.name = name</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> animal = <span class="keyword">new</span> Animal(<span class="string">&#x27;Goat&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> rhino = <span class="keyword">new</span> Rhino()</span><br><span class="line"><span class="keyword">let</span> employee = <span class="keyword">new</span> Employee(<span class="string">&#x27;Bob&#x27;</span>)</span><br><span class="line"></span><br><span class="line">animal = rhino</span><br><span class="line">animal = employee <span class="comment">// 错误: Animal 与 Employee 不兼容.</span></span><br></pre></td></tr></table></figure>

<p>这个例子中有 <code>Animal</code> 和 <code>Rhino</code> 两个类， <code>Rhino</code> 是 <code>Animal</code> 类的子类。 还有一个 <code>Employee</code> 类，其类型看上去与 <code>Animal</code> 是相同的。 我们创建了几个这些类的实例，并相互赋值来看看会发生什么。 因为 <code>Animal</code> 和 <code>Rhino</code> 共享了来自 <code>Animal</code> 里的私有成员定义 <code>private name: string</code>，因此它们是兼容的。然而 <code>Employee</code> 却不是这样。当把 <code>Employee</code> 赋值给 <code>Animal</code> 的时候，得到一个错误，说它们的类型不兼容。尽管 <code>Employee</code> 里也有一个私有成员 <code>name</code>，但它明显不是 <code>Animal</code> 里面定义的那个。</p>
<h3 id="4-3-3-理解-protected"><a href="#4-3-3-理解-protected" class="headerlink" title="4.3.3 理解 protected"></a>4.3.3 理解 protected</h3><p><code>protected</code> 修饰符与 <code>private</code> 修饰符的行为很相似，但有一点不同，<code>protected</code>成员在派生类中仍然可以访问。例如：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="keyword">protected</span> name: <span class="built_in">string</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123; </span><br><span class="line">        <span class="built_in">this</span>.name = name </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Employee</span> <span class="keyword">extends</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> department: <span class="built_in">string</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span>, department: <span class="built_in">string</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(name)</span><br><span class="line">        <span class="built_in">this</span>.department = department</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">getElevatorPitch</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">`Hello, my name is <span class="subst">$&#123;<span class="built_in">this</span>.name&#125;</span> and I work in <span class="subst">$&#123;<span class="built_in">this</span>.department&#125;</span>.`</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> howard = <span class="keyword">new</span> Employee(<span class="string">&#x27;Howard&#x27;</span>, <span class="string">&#x27;Sales&#x27;</span>)</span><br><span class="line"><span class="built_in">console</span>.log(howard.getElevatorPitch())</span><br><span class="line"><span class="built_in">console</span>.log(howard.name) <span class="comment">// error</span></span><br></pre></td></tr></table></figure>

<p>注意，我们不能在 <code>Person</code> 类外使用 <code>name</code>，但是我们仍然可以通过 <code>Employee</code> 类的实例方法访问，因为 <code>Employee</code> 是由 <code>Person</code> 派生而来的。</p>
<p>构造函数也可以被标记成 <code>protected</code>。 这意味着这个类不能在包含它的类外被实例化，但是能被继承。比如：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">  <span class="keyword">protected</span> name: <span class="built_in">string</span></span><br><span class="line">  <span class="keyword">protected</span> <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.name = name</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Employee 能够继承 Person</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Employee</span> <span class="keyword">extends</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">  <span class="keyword">private</span> department: <span class="built_in">string</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span>, department: <span class="built_in">string</span></span>)</span> &#123;</span><br><span class="line">    <span class="built_in">super</span>(name)</span><br><span class="line">    <span class="built_in">this</span>.department = department</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">public</span> <span class="function"><span class="title">getElevatorPitch</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">`Hello, my name is <span class="subst">$&#123;<span class="built_in">this</span>.name&#125;</span> and I work in <span class="subst">$&#123;<span class="built_in">this</span>.department&#125;</span>.`</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> howard = <span class="keyword">new</span> Employee(<span class="string">&#x27;Howard&#x27;</span>, <span class="string">&#x27;Sales&#x27;</span>)</span><br><span class="line"><span class="keyword">let</span> john = <span class="keyword">new</span> Person(<span class="string">&#x27;John&#x27;</span>) <span class="comment">// 错误: &#x27;Person&#x27; 的构造函数是被保护的.</span></span><br></pre></td></tr></table></figure>

<h2 id="4-4-readonly-修饰符"><a href="#4-4-readonly-修饰符" class="headerlink" title="4.4 readonly 修饰符"></a>4.4 readonly 修饰符</h2><p>你可以使用 <code>readonly</code> 关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="keyword">readonly</span> name: <span class="built_in">string</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> john = <span class="keyword">new</span> Person(<span class="string">&#x27;John&#x27;</span>)</span><br><span class="line">john.name = <span class="string">&#x27;peter&#x27;</span></span><br></pre></td></tr></table></figure>

<h3 id="4-4-1-参数属性"><a href="#4-4-1-参数属性" class="headerlink" title="4.4.1 参数属性"></a>4.4.1 参数属性</h3><p>在上面的例子中，我们必须在 <code>Person</code> 类里定义一个只读成员 <code>name</code> 和一个参数为 <code>name</code> 的构造函数，并且立刻将 <code>name</code> 的值赋给 <code>this.name</code>，这种情况经常会遇到。 参数属性可以方便地让我们在一个地方定义并初始化一个成员。 下面的例子是对之前 <code>Person</code> 类的修改版，使用了参数属性：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"><span class="keyword">readonly</span> name: <span class="built_in">string</span></span>)</span> &#123;&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意看我们是如何舍弃参数 <code>name</code>，仅在构造函数里使用 <code>readonly name: string</code> 参数来创建和初始化 <code>name</code> 成员。 我们把声明和赋值合并至一处。</p>
<p>参数属性通过给构造函数参数前面添加一个访问限定符来声明。使用 <code>private</code> 限定一个参数属性会声明并初始化一个私有成员；对于 <code>public</code> 和 <code>protected</code> 来说也是一样。</p>
<h2 id="4-5-存取器"><a href="#4-5-存取器" class="headerlink" title="4.5 存取器"></a>4.5 存取器</h2><p><code>TypeScript</code> 支持通过 <code>getters/setters</code> 来截取对对象成员的访问。 它能帮助你有效的控制对对象成员的访问。</p>
<p>下面来看如何把一个简单的类改写成使用 <code>get</code> 和 <code>set</code>。 首先，我们从一个没有使用存取器的例子开始。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Employee</span> </span>&#123;</span><br><span class="line">    fullName: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> employee = <span class="keyword">new</span> Employee()</span><br><span class="line">employee.fullName = <span class="string">&#x27;Bob Smith&#x27;</span></span><br><span class="line"><span class="keyword">if</span> (employee.fullName) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(employee.fullName)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们可以设置 <code>fullName</code>，因为它是 <code>public</code> 的，有时候当我们去修改它的时候触发一些额外逻辑，存取器就派上用场了。</p>
<p>下面这个版本里，我们先检查用户密码是否正确，然后再允许其修改员工信息。我们把对 <code>fullName</code> 的直接访问改成了可以检查密码的 <code>set</code> 方法。 我们也加了一个 <code>get</code> 方法，让上面的例子仍然可以工作。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> passcode = <span class="string">&#x27;secret passcode&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Employee</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> _fullName: <span class="built_in">string</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">get</span> <span class="title">fullName</span>(): <span class="title">string</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>._fullName</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">set</span> <span class="title">fullName</span>(<span class="params">newName: <span class="built_in">string</span></span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (passcode &amp;&amp; passcode == <span class="string">&#x27;secret passcode&#x27;</span>) &#123;</span><br><span class="line">            <span class="built_in">this</span>._fullName = newName</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;Error: Unauthorized update of employee!&#x27;</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> employee = <span class="keyword">new</span> Employee()</span><br><span class="line">employee.fullName = <span class="string">&#x27;Bob Smith&#x27;</span></span><br><span class="line"><span class="keyword">if</span> (employee.fullName) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(employee.fullName)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们可以修改一下密码，来验证一下存取器是否是工作的。当密码不对时，会提示我们没有权限去修改员工。</p>
<p>对于存取器有下面几点需要注意的：</p>
<p>首先，存取器要求你将编译器设置为输出 ECMAScript 5 或更高。 不支持降级到 ECMAScript 3。其次，只带有 <code>get</code> 不带有 <code>set</code> 的存取器自动被推断为 <code>readonly</code>。这在从代码生成 <code>.d.ts</code> 文件时是有帮助的，因为利用这个属性的用户会看到不允许够改变它的值。</p>
<h2 id="4-6-静态属性"><a href="#4-6-静态属性" class="headerlink" title="4.6 静态属性"></a>4.6 静态属性</h2><p>到目前为止，我们只讨论了类的实例成员，那些仅当类被实例化的时候才会被初始化的属性。 我们也可以创建类的静态成员，这些属性存在于类本身上面而不是类的实例上。 在这个例子里，我们使用 <code>static</code> 定义 <code>origin</code>，因为它是所有网格都会用到的属性。 每个实例想要访问这个属性的时候，都要在 <code>origin</code> 前面加上类名。 如同在实例属性上使用 <code>this.xxx</code> 来访问属性一样，这里我们使用 <code>Grid.xxx</code> 来访问静态属性。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Grid</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> origin = &#123;<span class="attr">x</span>: <span class="number">0</span>, <span class="attr">y</span>: <span class="number">0</span>&#125;</span><br><span class="line"></span><br><span class="line">    scale: <span class="built_in">number</span></span><br><span class="line"></span><br><span class="line">    <span class="title">constructor</span> (<span class="params">scale: <span class="built_in">number</span></span>) &#123;</span><br><span class="line">        <span class="built_in">this</span>.scale = scale</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">calculateDistanceFromOrigin</span>(<span class="params">point: &#123;x: <span class="built_in">number</span>; y: <span class="built_in">number</span>&#125;</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">let</span> xDist = point.x - Grid.origin.x</span><br><span class="line">        <span class="keyword">let</span> yDist = point.y - Grid.origin.y</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Math</span>.sqrt(xDist * xDist + yDist * yDist) * <span class="built_in">this</span>.scale</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> grid1 = <span class="keyword">new</span> Grid(<span class="number">1.0</span>)  <span class="comment">// 1x scale</span></span><br><span class="line"><span class="keyword">let</span> grid2 = <span class="keyword">new</span> Grid(<span class="number">5.0</span>)  <span class="comment">// 5x scale</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(grid1.calculateDistanceFromOrigin(&#123;<span class="attr">x</span>: <span class="number">3</span>, <span class="attr">y</span>: <span class="number">4</span>&#125;))</span><br><span class="line"><span class="built_in">console</span>.log(grid2.calculateDistanceFromOrigin(&#123;<span class="attr">x</span>: <span class="number">3</span>, <span class="attr">y</span>: <span class="number">4</span>&#125;))</span><br></pre></td></tr></table></figure>

<h2 id="4-7-抽象类"><a href="#4-7-抽象类" class="headerlink" title="4.7 抽象类"></a>4.7 抽象类</h2><p>抽象类做为其它派生类的基类使用。 它们一般不会直接被实例化。不同于接口，抽象类可以包含成员的实现细节。 <code>abstract</code> 关键字是用于定义抽象类和在抽象类内部定义抽象方法。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    <span class="keyword">abstract</span> makeSound(): <span class="built_in">void</span></span><br><span class="line">    move(): <span class="built_in">void</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;roaming the earth...&#x27;</span>)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。 抽象方法的语法与接口方法相似。两者都是定义方法签名但不包含方法体。 然而，抽象方法必须包含 <code>abstract</code> 关键字并且可以包含访问修饰符。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">Department</span> </span>&#123;</span><br><span class="line">    name: <span class="built_in">string</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">name: <span class="built_in">string</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.name = name</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    printName(): <span class="built_in">void</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Department name: &#x27;</span> + <span class="built_in">this</span>.name)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">abstract</span> printMeeting(): <span class="built_in">void</span> <span class="comment">// 必须在派生类中实现</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AccountingDepartment</span> <span class="keyword">extends</span> <span class="title">Department</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">super</span>(<span class="string">&#x27;Accounting and Auditing&#x27;</span>) <span class="comment">// 在派生类的构造函数中必须调用 super()</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    printMeeting(): <span class="built_in">void</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;The Accounting Department meets each Monday at 10am.&#x27;</span>)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">    generateReports(): <span class="built_in">void</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;Generating accounting reports...&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> department: Department <span class="comment">// 允许创建一个对抽象类型的引用</span></span><br><span class="line">department = <span class="keyword">new</span> Department() <span class="comment">// 错误: 不能创建一个抽象类的实例</span></span><br><span class="line">department = <span class="keyword">new</span> AccountingDepartment() <span class="comment">// 允许对一个抽象子类进行实例化和赋值</span></span><br><span class="line">department.printName()</span><br><span class="line">department.printMeeting()</span><br><span class="line">department.generateReports() <span class="comment">// 错误: 方法在声明的抽象类中不存在</span></span><br></pre></td></tr></table></figure>

<h2 id="4-8-高级技巧"><a href="#4-8-高级技巧" class="headerlink" title="4.8 高级技巧"></a>4.8 高级技巧</h2><h3 id="4-8-1-构造函数"><a href="#4-8-1-构造函数" class="headerlink" title="4.8.1 构造函数"></a>4.8.1 构造函数</h3><p>当你在 TypeScript 里声明了一个类的时候，实际上同时声明了很多东西。首先就是类的<em>实例</em>的类型。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Greeter</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> standardGreeting = <span class="string">&#x27;Hello, there&#x27;</span></span><br><span class="line">    greeting: <span class="built_in">string</span></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">message: <span class="built_in">string</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.greeting = message</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">greet</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;Hello, &#x27;</span> + <span class="built_in">this</span>.greeting</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> greeter: Greeter</span><br><span class="line">greeter = <span class="keyword">new</span> Greeter(<span class="string">&#x27;world&#x27;</span>)</span><br><span class="line"><span class="built_in">console</span>.log(greeter.greet())</span><br></pre></td></tr></table></figure>

<p>这里，我们写了 <code>let greeter: Greeter</code>，意思是 <code>Greeter</code> 类的实例的类型是 <code>Greeter</code>。 这对于用过其它面向对象语言的程序员来讲已经是老习惯了。</p>
<p>我们也创建了一个叫做<em>构造函数的值</em>。 这个函数会在我们使用 <code>new</code> 创建类实例的时候被调用。 下面我们来看看，上面的代码被编译成JavaScript后是什么样子的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Greeter = <span class="comment">/** <span class="doctag">@class </span>*/</span> (<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">Greeter</span>(<span class="params">message</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.greeting = message;</span><br><span class="line">    &#125;</span><br><span class="line">    Greeter.prototype.greet = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;Hello, &#x27;</span> + <span class="built_in">this</span>.greeting;</span><br><span class="line">    &#125;;</span><br><span class="line">    Greeter.standardGreeting = <span class="string">&#x27;Hello, there&#x27;</span>;</span><br><span class="line">    <span class="keyword">return</span> Greeter;</span><br><span class="line">&#125;());</span><br><span class="line"><span class="keyword">var</span> greeter;</span><br><span class="line">greeter = <span class="keyword">new</span> Greeter(<span class="string">&#x27;world&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(greeter.greet());</span><br></pre></td></tr></table></figure>

<p>上面的代码里，<code>var Greeter</code> 将被构造函数赋值。 当我们调用 <code>new</code> 并执行了这个函数后，便会得到一个类的实例。这个构造函数也包含了类的所有静态属性。 换个角度说，我们可以认为类具有<em>实例部分</em>与<em>静态部分</em>这两个部分。</p>
<p>让我们稍微改写一下这个例子，看看它们之间的区别：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Greeter</span> </span>&#123;</span><br><span class="line">    <span class="keyword">static</span> standardGreeting = <span class="string">&#x27;Hello, there&#x27;</span></span><br><span class="line"></span><br><span class="line">    greeting: <span class="built_in">string</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">message?: <span class="built_in">string</span></span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.greeting = message</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">greet</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">this</span>.greeting) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&#x27;Hello, &#x27;</span> + <span class="built_in">this</span>.greeting</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> Greeter.standardGreeting</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> greeter: Greeter</span><br><span class="line">greeter = <span class="keyword">new</span> Greeter()</span><br><span class="line"><span class="built_in">console</span>.log(greeter.greet())</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> greeterMaker: <span class="keyword">typeof</span> Greeter = Greeter</span><br><span class="line">greeterMaker.standardGreeting = <span class="string">&#x27;Hey there&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> greeter2: Greeter = <span class="keyword">new</span> greeterMaker()</span><br><span class="line"><span class="built_in">console</span>.log(greeter2.greet())</span><br></pre></td></tr></table></figure>

<p>这个例子里， <code>greeter1</code> 与之前看到的一样。 我们实例化 Greeter类，并使用这个对象。 与我们之前看到的一样。</p>
<p>再之后，我们直接使用类。 我们创建了一个叫做 <code>greeterMaker</code> 的变量。这个变量保存了这个类或者说保存了类构造函数。 然后我们使用 <code>typeof Greeter</code>，意思是取 <code>Greeter</code> 类的类型，而不是实例的类型。或者更确切的说，”告诉我 <code>Greeter</code> 标识符的类型”，也就是构造函数的类型。 这个类型包含了类的所有静态成员和构造函数。 之后，就和前面一样，我们在 <code>greeterMaker</code> 上使用 <code>new</code>，创建 <code>Greeter</code> 的实例。</p>
<h3 id="4-8-2-把类当做接口使用"><a href="#4-8-2-把类当做接口使用" class="headerlink" title="4.8.2 把类当做接口使用"></a>4.8.2 把类当做接口使用</h3><p>如上一节里所讲的，类定义会创建两个东西：类的实例类型和一个构造函数。 因为类可以创建出类型，所以你能够在允许使用接口的地方使用类。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Point</span> </span>&#123;</span><br><span class="line">    x: <span class="built_in">number</span></span><br><span class="line">    y: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> Point3d <span class="keyword">extends</span> Point &#123;</span><br><span class="line">    z: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> point3d: Point3d = &#123;<span class="attr">x</span>: <span class="number">1</span>, <span class="attr">y</span>: <span class="number">2</span>, <span class="attr">z</span>: <span class="number">3</span>&#125;</span><br></pre></td></tr></table></figure>

<h1 id="5-函数"><a href="#5-函数" class="headerlink" title="5.函数"></a>5.函数</h1><p>函数是 JavaScript 应用程序的基础，它帮助你实现抽象层，模拟类，信息隐藏和模块。在 TypeScript 里，虽然已经支持类，命名空间和模块，但函数仍然是主要的定义行为的地方。TypeScript 为 JavaScript 函数添加了额外的功能，让我们可以更容易地使用。</p>
<h2 id="5-1-基本示例"><a href="#5-1-基本示例" class="headerlink" title="5.1 基本示例"></a>5.1 基本示例</h2><p>和 JavaScript 一样，TypeScript 函数可以创建有名字的函数和匿名函数。你可以随意选择适合应用程序的方式，不论是定义一系列 API 函数还是只使用一次的函数。</p>
<p>通过下面的例子可以迅速回想起这两种 JavaScript 中的函数：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 命名函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> x + y</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 匿名函数</span></span><br><span class="line"><span class="keyword">let</span> myAdd = <span class="function"><span class="keyword">function</span>(<span class="params">x, y</span>) </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 JavaScript 里，函数可以使用函数体外部的变量。 当函数这么做时，我们说它‘捕获’了这些变量。 至于为什么可以这样做以及其中的利弊超出了本文的范围，但是深刻理解这个机制对学习 JavaScript 和 TypeScript 会很有帮助。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> z = <span class="number">100</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">addToZ</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> x + y + z;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-2-函数类型"><a href="#5-2-函数类型" class="headerlink" title="5.2 函数类型"></a>5.2 函数类型</h2><h3 id="5-2-1-为函数定义类型"><a href="#5-2-1-为函数定义类型" class="headerlink" title="5.2.1 为函数定义类型"></a>5.2.1 为函数定义类型</h3><p>让我们为上面那个函数添加类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x: <span class="built_in">number</span>, y: <span class="built_in">number</span></span>): <span class="title">number</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myAdd = <span class="function"><span class="keyword">function</span>(<span class="params">x: <span class="built_in">number</span>, y: <span class="built_in">number</span></span>): <span class="title">number</span> </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们可以给每个参数添加类型之后再为函数本身添加返回值类型。TypeScript 能够根据返回语句自动推断出返回值类型。</p>
<h3 id="5-2-2-书写完整函数类型"><a href="#5-2-2-书写完整函数类型" class="headerlink" title="5.2.2 书写完整函数类型"></a>5.2.2 书写完整函数类型</h3><p>现在我们已经为函数指定了类型，下面让我们写出函数的完整类型。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> myAdd: <span class="function">(<span class="params">x: <span class="built_in">number</span>, y: <span class="built_in">number</span></span>) =&gt;</span> <span class="built_in">number</span> = </span><br><span class="line">    <span class="function"><span class="keyword">function</span>(<span class="params">x: <span class="built_in">number</span>, y: <span class="built_in">number</span></span>): <span class="title">number</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> x + y;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>函数类型包含两部分：参数类型和返回值类型。 当写出完整函数类型的时候，这两部分都是需要的。 我们以参数列表的形式写出参数类型，为每个参数指定一个名字和类型。这个名字只是为了增加可读性。 我们也可以这么写：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> myAdd: <span class="function">(<span class="params">baseValue: <span class="built_in">number</span>, increment: <span class="built_in">number</span></span>) =&gt;</span> <span class="built_in">number</span> = </span><br><span class="line">    <span class="function"><span class="keyword">function</span>(<span class="params">x: <span class="built_in">number</span>, y: <span class="built_in">number</span></span>): <span class="title">number</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> x + y;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>只要参数类型是匹配的，那么就认为它是有效的函数类型，而不在乎参数名是否正确。</p>
<p>第二部分是返回值类型。对于返回值，我们在函数和返回值类型之前使用(<code>=&gt;</code>)符号，使之清晰明了。 如之前提到的，返回值类型是函数类型的必要部分，如果函数没有返回任何值，你也必须指定返回值类型为 <code>void</code> 而不能留空。</p>
<p>函数的类型只是由参数类型和返回值组成的。 函数中使用的捕获变量不会体现在类型里。 实际上，这些变量是函数的隐藏状态并不是组成 API 的一部分。</p>
<h3 id="5-2-3-推断类型"><a href="#5-2-3-推断类型" class="headerlink" title="5.2.3 推断类型"></a>5.2.3 推断类型</h3><p>尝试这个例子的时候，你会发现如果你在赋值语句的一边指定了类型但是另一边没有类型的话，TypeScript 编译器会自动识别出类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> myAdd = <span class="function"><span class="keyword">function</span>(<span class="params">x: <span class="built_in">number</span>, y: <span class="built_in">number</span></span>): <span class="title">number</span> </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myAdd: <span class="function">(<span class="params">baseValue: <span class="built_in">number</span>, increment: <span class="built_in">number</span></span>) =&gt;</span> <span class="built_in">number</span> = </span><br><span class="line">    <span class="function"><span class="keyword">function</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> x + y;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>这叫做“按上下文归类”，是类型推论的一种。它帮助我们更好地为程序指定类型。</p>
<h2 id="5-3-可选参数和默认参数"><a href="#5-3-可选参数和默认参数" class="headerlink" title="5.3 可选参数和默认参数"></a>5.3 可选参数和默认参数</h2><p>TypeScript 里的每个函数参数都是必须的。 这不是指不能传递 <code>null</code> 或 <code>undefined</code> 作为参数，而是说编译器检查用户是否为每个参数都传入了值。编译器还会假设只有这些参数会被传递进函数。 简短地说，传递给一个函数的参数个数必须与函数期望的参数个数一致。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">buildName</span>(<span class="params">firstName: <span class="built_in">string</span>, lastName: <span class="built_in">string</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> firstName + <span class="string">&#x27; &#x27;</span> + lastName;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> result1 = buildName(<span class="string">&#x27;Bob&#x27;</span>);                  <span class="comment">// Error, 参数过少</span></span><br><span class="line"><span class="keyword">let</span> result2 = buildName(<span class="string">&#x27;Bob&#x27;</span>, <span class="string">&#x27;Adams&#x27;</span>, <span class="string">&#x27;Sr.&#x27;</span>);  <span class="comment">// Error, 参数过多</span></span><br><span class="line"><span class="keyword">let</span> result3 = buildName(<span class="string">&#x27;Bob&#x27;</span>, <span class="string">&#x27;Adams&#x27;</span>);         <span class="comment">// OK</span></span><br></pre></td></tr></table></figure>

<p>JavaScript 里，每个参数都是可选的，可传可不传。 没传参的时候，它的值就是 <code>undefined</code>。 在TypeScript 里我们可以在参数名旁使用 <code>?</code> 实现可选参数的功能。 比如，我们想让 <code>lastName</code> 是可选的：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">buildName</span>(<span class="params">firstName: <span class="built_in">string</span>, lastName?: <span class="built_in">string</span></span>): <span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (lastName)</span><br><span class="line">        <span class="keyword">return</span> firstName + <span class="string">&#x27; &#x27;</span> + lastName;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        <span class="keyword">return</span> firstName;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> result1 = buildName(<span class="string">&#x27;Bob&#x27;</span>);  <span class="comment">// 现在正常了</span></span><br><span class="line"><span class="keyword">let</span> result2 = buildName(<span class="string">&#x27;Bob&#x27;</span>, <span class="string">&#x27;Adams&#x27;</span>, <span class="string">&#x27;Sr.&#x27;</span>);  <span class="comment">// Error, 参数过多</span></span><br><span class="line"><span class="keyword">let</span> result3 = buildName(<span class="string">&#x27;Bob&#x27;</span>, <span class="string">&#x27;Adams&#x27;</span>);  <span class="comment">// OK</span></span><br></pre></td></tr></table></figure>

<p>可选参数必须跟在必须参数后面。 如果上例我们想让 <code>firstName</code> 是可选的，那么就必须调整它们的位置，把 <code>firstName</code> 放在后面。</p>
<p>在 TypeScript 里，我们也可以为参数提供一个默认值当用户没有传递这个参数或传递的值是 <code>undefined</code> 时。 它们叫做有默认初始化值的参数。 让我们修改上例，把<code>lastName</code> 的默认值设置为 <code>&quot;Smith&quot;</code>。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">buildName</span>(<span class="params">firstName: <span class="built_in">string</span>, lastName = <span class="string">&#x27;Smith&#x27;</span></span>): <span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> firstName + <span class="string">&#x27; &#x27;</span> + lastName;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> result1 = buildName(<span class="string">&#x27;Bob&#x27;</span>)                  <span class="comment">// 返回 &quot;Bob Smith&quot;</span></span><br><span class="line"><span class="keyword">let</span> result2 = buildName(<span class="string">&#x27;Bob&#x27;</span>, <span class="literal">undefined</span>)     <span class="comment">// 正常, 同样 &quot;Bob Smith&quot;</span></span><br><span class="line"><span class="keyword">let</span> result3 = buildName(<span class="string">&#x27;Bob&#x27;</span>, <span class="string">&#x27;Adams&#x27;</span>, <span class="string">&#x27;Sr.&#x27;</span>)  <span class="comment">// 错误, 参数过多</span></span><br><span class="line"><span class="keyword">let</span> result4 = buildName(<span class="string">&#x27;Bob&#x27;</span>, <span class="string">&#x27;Adams&#x27;</span>)        <span class="comment">// OK</span></span><br></pre></td></tr></table></figure>

<p>与普通可选参数不同的是，带默认值的参数不需要放在必须参数的后面。 如果带默认值的参数出现在必须参数前面，用户必须明确的传入 <code>undefined</code> 值来获得默认值。 例如，我们重写最后一个例子，让 <code>firstName</code> 是带默认值的参数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">buildName</span>(<span class="params">firstName = <span class="string">&#x27;Will&#x27;</span>, lastName: <span class="built_in">string</span></span>): <span class="title">string</span> </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> firstName + <span class="string">&#x27; &#x27;</span> + lastName</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> result1 = buildName(<span class="string">&#x27;Bob&#x27;</span>)                  <span class="comment">// Error, 参数过少</span></span><br><span class="line"><span class="keyword">let</span> result2 = buildName(<span class="string">&#x27;Bob&#x27;</span>, <span class="string">&#x27;Adams&#x27;</span>, <span class="string">&quot;Sr.&quot;</span>)  <span class="comment">// Error, 参数过多</span></span><br><span class="line"><span class="keyword">let</span> result3 = buildName(<span class="string">&#x27;Bob&#x27;</span>, <span class="string">&#x27;Adams&#x27;</span>)         <span class="comment">// OK， 返回 &quot;Bob Adams&quot;</span></span><br><span class="line"><span class="keyword">let</span> result4 = buildName(<span class="literal">undefined</span>, <span class="string">&#x27;Adams&#x27;</span>)     <span class="comment">// OK，  返回 &quot;Will Adams&quot;</span></span><br></pre></td></tr></table></figure>

<h3 id="5-3-1-剩余参数"><a href="#5-3-1-剩余参数" class="headerlink" title="5.3.1 剩余参数"></a>5.3.1 剩余参数</h3><p>必要参数，默认参数和可选参数有个共同点：它们表示某一个参数。 有时，你想同时操作多个参数，或者你并不知道会有多少参数传递进来。 在 JavaScript 里，你可以使用 <code>arguments</code> 来访问所有传入的参数。</p>
<p>在 TypeScript 里，你可以把所有参数收集到一个变量里：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">buildName</span>(<span class="params">firstName: <span class="built_in">string</span>, ...restOfName: <span class="built_in">string</span>[]</span>): <span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> firstName + <span class="string">&#x27; &#x27;</span> + restOfName.join(<span class="string">&#x27; &#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> employeeName = buildName(<span class="string">&#x27;Joseph&#x27;</span>, <span class="string">&#x27;Samuel&#x27;</span>, <span class="string">&#x27;Lucas&#x27;</span>, <span class="string">&#x27;MacKinzie&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>剩余参数会被当做个数不限的可选参数。 可以一个都没有，同样也可以有任意个。 编译器创建参数数组，名字是你在省略号（ <code>...</code>）后面给定的名字，你可以在函数体内使用这个数组。</p>
<p>这个省略号也会在带有剩余参数的函数类型定义上使用到：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">buildName</span>(<span class="params">firstName: <span class="built_in">string</span>, ...restOfName: <span class="built_in">string</span>[]</span>): <span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> firstName + <span class="string">&#x27; &#x27;</span> + restOfName.join(<span class="string">&#x27; &#x27;</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> buildNameFun: <span class="function">(<span class="params">fname: <span class="built_in">string</span>, ...rest: <span class="built_in">string</span>[]</span>) =&gt;</span> <span class="built_in">string</span> = buildName</span><br></pre></td></tr></table></figure>

<h2 id="5-4-this"><a href="#5-4-this" class="headerlink" title="5.4 this"></a>5.4 this</h2><p>学习如何在 JavaScript 里正确使用 <code>this</code> 就好比一场成年礼。由于 TypeScript 是 JavaScript 的超集，TypeScript 程序员也需要弄清 <code>this</code> 工作机制并且当有 bug 的时候能够找出错误所在。 幸运的是，TypeScript 能通知你错误地使用了 <code>this</code> 的地方。 如果你想了解 JavaScript 里的 this是如何工作的，那么首先阅读 Yehuda Katz 写的 <a target="_blank" rel="noopener" href="http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/">Understanding JavaScript Function Invocation and “this” (opens new window)</a>。 Yehuda 的文章详细的阐述了 <code>this</code> 的内部工作原理，因此我们这里只做简单介绍。</p>
<h3 id="5-4-1-this-和箭头函数"><a href="#5-4-1-this-和箭头函数" class="headerlink" title="5.4.1 this 和箭头函数"></a>5.4.1 this 和箭头函数</h3><p>JavaScript里，<code>this</code> 的值在函数被调用的时候才会指定。 这是个既强大又灵活的特点，但是你需要花点时间弄清楚函数调用的上下文是什么。但众所周知，这不是一件很简单的事，尤其是在返回一个函数或将函数当做参数传递的时候。</p>
<p>下面看一个例子：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> deck = &#123;</span><br><span class="line">    suits: [<span class="string">&#x27;hearts&#x27;</span>, <span class="string">&#x27;spades&#x27;</span>, <span class="string">&#x27;clubs&#x27;</span>, <span class="string">&#x27;diamonds&#x27;</span>],</span><br><span class="line">    cards: <span class="built_in">Array</span>(<span class="number">52</span>),</span><br><span class="line">    createCardPicker: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">let</span> pickedCard = <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * <span class="number">52</span>);</span><br><span class="line">            <span class="keyword">let</span> pickedSuit = <span class="built_in">Math</span>.floor(pickedCard / <span class="number">13</span>);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> &#123;</span><br><span class="line">                suit: <span class="built_in">this</span>.suits[pickedSuit],</span><br><span class="line">                card: pickedCard % <span class="number">13</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> cardPicker = deck.createCardPicker();</span><br><span class="line"><span class="keyword">let</span> pickedCard = cardPicker();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;card: &#x27;</span> + pickedCard.card + <span class="string">&#x27; of &#x27;</span> + pickedCard.suit);</span><br></pre></td></tr></table></figure>

<p>可以看到 <code>createCardPicker</code> 是个函数，并且它又返回了一个函数。如果我们尝试运行这个程序，会发现它并没有输出而是报错了。 因为 <code>createCardPicker</code> 返回的函数里的 <code>this</code> 被设置成了 <code>global</code> 而不是 <code>deck</code> 对象。 因为我们只是独立的调用了 <code>cardPicker()</code>。 顶级的非方法式调用会将 <code>this</code> 视为 <code>global</code>。</p>
<p>为了解决这个问题，我们可以在函数被返回时就绑好正确的<code>this</code>。 这样的话，无论之后怎么使用它，都会引用绑定的<code>deck</code> 对象。 我们需要改变函数表达式来使用 ECMAScript 6 箭头语法。 箭头函数能保存函数创建时的 <code>this</code> 值，而不是调用时的值：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> deck = &#123;</span><br><span class="line">    suits: [<span class="string">&#x27;hearts&#x27;</span>, <span class="string">&#x27;spades&#x27;</span>, <span class="string">&#x27;clubs&#x27;</span>, <span class="string">&#x27;diamonds&#x27;</span>],</span><br><span class="line">    cards: <span class="built_in">Array</span>(<span class="number">52</span>),</span><br><span class="line">    createCardPicker: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="comment">// 注意：这里使用箭头函数</span></span><br><span class="line">        <span class="keyword">return</span> <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">let</span> pickedCard = <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * <span class="number">52</span>);</span><br><span class="line">            <span class="keyword">let</span> pickedSuit = <span class="built_in">Math</span>.floor(pickedCard / <span class="number">13</span>);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> &#123;</span><br><span class="line">                suit: <span class="built_in">this</span>.suits[pickedSuit],</span><br><span class="line">                card: pickedCard % <span class="number">13</span></span><br><span class="line">            &#125;;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> cardPicker = deck.createCardPicker();</span><br><span class="line"><span class="keyword">let</span> pickedCard = cardPicker();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;card: &#x27;</span> + pickedCard.card + <span class="string">&#x27; of &#x27;</span> + pickedCard.suit); <span class="comment">// card: 2 of hearts</span></span><br></pre></td></tr></table></figure>

<h3 id="5-4-2-this-参数"><a href="#5-4-2-this-参数" class="headerlink" title="5.4.2 this 参数"></a>5.4.2 this 参数</h3><p>在上述的例子中 <code>this.suits[pickedSuit]</code> 的类型为 <code>any</code>，这是因为 <code>this</code> 来自对象字面量里的函数表达式。 修改的方法是，提供一个显式的 <code>this</code> 参数。 <code>this</code> 参数是个假的参数，它出现在参数列表的最前面：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"><span class="built_in">this</span>: <span class="built_in">void</span></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 确保“this”在此独立函数中不可用</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>让我们往例子里添加一些接口，<code>Card</code> 和 <code>Deck</code>，让类型重用能够变得清晰简单些：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Card &#123;</span><br><span class="line">    suit: <span class="built_in">string</span>,</span><br><span class="line">    card: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> Deck &#123;</span><br><span class="line">    suits: <span class="built_in">string</span>[],</span><br><span class="line">    cards: <span class="built_in">number</span>[],</span><br><span class="line"></span><br><span class="line">    createCardPicker (<span class="built_in">this</span>: Deck): <span class="function">() =&gt;</span> Card</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> deck: Deck = &#123;</span><br><span class="line">    suits: [<span class="string">&#x27;hearts&#x27;</span>, <span class="string">&#x27;spades&#x27;</span>, <span class="string">&#x27;clubs&#x27;</span>, <span class="string">&#x27;diamonds&#x27;</span>],</span><br><span class="line">    cards: <span class="built_in">Array</span>(<span class="number">52</span>),</span><br><span class="line">    <span class="comment">// <span class="doctag">NOTE:</span> 函数现在显式指定其被调用方必须是 deck 类型</span></span><br><span class="line">    createCardPicker: <span class="function"><span class="keyword">function</span> (<span class="params"><span class="built_in">this</span>: Deck</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">let</span> pickedCard = <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * <span class="number">52</span>);</span><br><span class="line">            <span class="keyword">let</span> pickedSuit = <span class="built_in">Math</span>.floor(pickedCard / <span class="number">13</span>);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> &#123;</span><br><span class="line">                suit: <span class="built_in">this</span>.suits[pickedSuit],</span><br><span class="line">                card: pickedCard % <span class="number">13</span></span><br><span class="line">            &#125;;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> cardPicker = deck.createCardPicker();</span><br><span class="line"><span class="keyword">let</span> pickedCard = cardPicker();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;card: &#x27;</span> + pickedCard.card + <span class="string">&#x27; of &#x27;</span> + pickedCard.suit); <span class="comment">// card: 1 of diamonds</span></span><br></pre></td></tr></table></figure>

<p>现在 TypeScrip t知道 <code>createCardPicker</code> 期望在某个 <code>Deck</code> 对象上调用。也就是说 <code>this</code> 是 <code>Deck</code> 类型的，而非 <code>any</code>。</p>
<h3 id="5-4-3-this-参数在回调函数里"><a href="#5-4-3-this-参数在回调函数里" class="headerlink" title="5.4.3 this 参数在回调函数里"></a>5.4.3 this 参数在回调函数里</h3><p>你可以也看到过在回调函数里的 <code>this</code> 报错，当你将一个函数传递到某个库函数里稍后会被调用时。 因为当回调被调用的时候，它们会被当成一个普通函数调用，<code>this</code> 将为 <code>undefined</code>。 稍做改动，你就可以通过 <code>this</code> 参数来避免错误。 首先，库函数的作者要指定 <code>this</code> 的类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> UIElement &#123;</span><br><span class="line">    addClickListener(onclick: <span class="function">(<span class="params"><span class="built_in">this</span>: <span class="built_in">void</span>, e: Event</span>) =&gt;</span> <span class="built_in">void</span>): <span class="built_in">void</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">this</span>: <span class="built_in">void</span><span class="string">` 意味着 `</span>addClickListener<span class="string">` 期望传入的 `</span>onclick<span class="string">` 方法不需要 `</span><span class="built_in">this</span></span><br><span class="line"><span class="keyword">interface</span> UIElement &#123;</span><br><span class="line">    addClickListener (onclick: <span class="function">(<span class="params"><span class="built_in">this</span>: <span class="built_in">void</span>, e: Event</span>) =&gt;</span> <span class="built_in">void</span>): <span class="built_in">void</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Handler</span> </span>&#123;</span><br><span class="line">    <span class="keyword">type</span>: <span class="built_in">string</span></span><br><span class="line"></span><br><span class="line">    onClickBad (<span class="built_in">this</span>: Handler, <span class="attr">e</span>: Event) &#123;</span><br><span class="line">        <span class="built_in">this</span>.type = e.type</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> h = <span class="keyword">new</span> Handler()</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> uiElement: UIElement = &#123;</span><br><span class="line">    addClickListener () &#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">uiElement.addClickListener(h.onClickBad) <span class="comment">// error!</span></span><br></pre></td></tr></table></figure>

<p>指定了 <code>this</code> 类型后，你显式声明 <code>onClickBad</code> 必须在 <code>Handler</code> 的实例上调用。 然后 TypeScript 会检测到 <code>addClickListener</code> 要求函数带有 <code>this: void</code>。 改变 <code>this</code> 类型来修复这个错误：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Handler</span> </span>&#123;</span><br><span class="line">    <span class="keyword">type</span>: <span class="built_in">string</span>;</span><br><span class="line"></span><br><span class="line">    onClickBad (<span class="built_in">this</span>: <span class="built_in">void</span>, <span class="attr">e</span>: Event) &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;clicked!&#x27;</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> h = <span class="keyword">new</span> Handler()</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> uiElement: UIElement = &#123;</span><br><span class="line">    addClickListener () &#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">uiElement.addClickListener(h.onClickBad)</span><br></pre></td></tr></table></figure>

<p>因为 <code>onClickGood</code> 指定了 <code>this</code> 类型为 <code>void</code>，因此传递 <code>addClickListener</code> 是合法的。 当然了，这也意味着不能使用 <code>this.info</code>。 如果你两者都想要，你不得不使用箭头函数了：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Handler</span> </span>&#123;</span><br><span class="line">    <span class="keyword">type</span>: <span class="built_in">string</span></span><br><span class="line">    onClickGood = <span class="function">(<span class="params">e: Event</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.type = e.type;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这是可行的因为箭头函数不会捕获 <code>this</code>，所以你总是可以把它们传给期望 <code>this: void</code> 的函数。</p>
<h2 id="5-5-重载"><a href="#5-5-重载" class="headerlink" title="5.5 重载"></a>5.5 重载</h2><p>JavaScript 本身是个动态语言。JavaScript 里函数根据传入不同的参数而返回不同类型的数据的场景是很常见的。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> suits = [<span class="string">&#x27;hearts&#x27;</span>, <span class="string">&#x27;spades&#x27;</span>, <span class="string">&#x27;clubs&#x27;</span>, <span class="string">&#x27;diamonds&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pickCard</span>(<span class="params">x</span>): <span class="title">any</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(x)) &#123;</span><br><span class="line">        <span class="keyword">let</span> pickedCard = <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * x.length);</span><br><span class="line">        <span class="keyword">return</span> pickedCard;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> x === <span class="string">&#x27;number&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> pickedSuit = <span class="built_in">Math</span>.floor(x / <span class="number">13</span>);</span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            suit: suits[pickedSuit],</span><br><span class="line">            card: x % <span class="number">13</span></span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myDeck = [</span><br><span class="line">    &#123; <span class="attr">suit</span>: <span class="string">&#x27;diamonds&#x27;</span>, <span class="attr">card</span>: <span class="number">2</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">suit</span>: <span class="string">&#x27;spades&#x27;</span>, <span class="attr">card</span>: <span class="number">10</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">suit</span>: <span class="string">&#x27;hearts&#x27;</span>, <span class="attr">card</span>: <span class="number">4</span> &#125;</span><br><span class="line">]</span><br><span class="line"><span class="keyword">let</span> pickedCard1 = myDeck[pickCard(myDeck)];</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;card: &#x27;</span> + pickedCard1.card + <span class="string">&#x27; of &#x27;</span> + pickedCard1.suit) <span class="comment">// card: 10 of spades</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> pickedCard2 = pickCard(<span class="number">15</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;card: &#x27;</span> + pickedCard2.card + <span class="string">&#x27; of &#x27;</span> + pickedCard2.suit) <span class="comment">// card: 2 of spades</span></span><br></pre></td></tr></table></figure>

<p><code>pickCard</code> 方法根据传入参数的不同会返回两种不同的类型。如果传入的是代表纸牌的对象数组，函数作用是从中抓一张牌。如果用户想抓牌，我们告诉他抓到了什么牌。 但是这怎么在类型系统里表示呢。</p>
<p>方法是为同一个函数提供多个函数类型定义来进行函数重载。 编译器会根据这个列表去处理函数的调用。 下面我们来重载 <code>pickCard</code> 函数。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> suits = [<span class="string">&#x27;hearts&#x27;</span>, <span class="string">&#x27;spades&#x27;</span>, <span class="string">&#x27;clubs&#x27;</span>, <span class="string">&#x27;diamonds&#x27;</span>]</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pickCard</span>(<span class="params">x: &#123;suit: <span class="built_in">string</span>; card: <span class="built_in">number</span> &#125;[]</span>): <span class="title">number</span></span></span><br><span class="line"><span class="function"><span class="function"><span class="keyword">function</span> <span class="title">pickCard</span>(<span class="params">x: <span class="built_in">number</span></span>): </span>&#123;<span class="title">suit</span>: <span class="title">string</span></span>; card: <span class="built_in">number</span> &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pickCard</span>(<span class="params">x</span>): <span class="title">any</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(x)) &#123;</span><br><span class="line">        <span class="keyword">let</span> pickedCard = <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * x.length);</span><br><span class="line">        <span class="keyword">return</span> pickedCard;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> x === <span class="string">&#x27;number&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> pickedSuit = <span class="built_in">Math</span>.floor(x / <span class="number">13</span>);</span><br><span class="line">        <span class="keyword">return</span> &#123; <span class="attr">suit</span>: suits[pickedSuit], <span class="attr">card</span>: x % <span class="number">13</span> &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myDeck = [</span><br><span class="line">    &#123; <span class="attr">suit</span>: <span class="string">&#x27;diamonds&#x27;</span>, <span class="attr">card</span>: <span class="number">2</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">suit</span>: <span class="string">&#x27;spades&#x27;</span>, <span class="attr">card</span>: <span class="number">10</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">suit</span>: <span class="string">&#x27;hearts&#x27;</span>, <span class="attr">card</span>: <span class="number">4</span> &#125;</span><br><span class="line">]</span><br><span class="line"><span class="keyword">let</span> pickedCard1 = myDeck[pickCard(myDeck)];</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;card: &#x27;</span> + pickedCard1.card + <span class="string">&#x27; of &#x27;</span> + pickedCard1.suit); <span class="comment">// card: 4 of hearts</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> pickedCard2 = pickCard(<span class="number">15</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;card: &#x27;</span> + pickedCard2.card + <span class="string">&#x27; of &#x27;</span> + pickedCard2.suit); <span class="comment">// card: 2 of spades</span></span><br></pre></td></tr></table></figure>

<p>这样改变后，重载的 <code>pickCard</code> 函数在调用的时候会进行正确的类型检查。</p>
<p>为了让编译器能够选择正确的检查类型，它与 JavaScript 里的处理流程相似。它查找重载列表，尝试使用第一个重载定义。 如果匹配的话就使用这个。因此，在定义重载的时候，一定要把最精确的定义放在最前面。</p>
<p>注意，<code>function pickCard(x): any</code> 并不是重载列表的一部分，因此这里只有两个重载：一个是接收对象数组，另一个接收数字。 以其它参数调用 <code>pickCard</code> 会产生错误。</p>
<h1 id="6-泛型"><a href="#6-泛型" class="headerlink" title="6.泛型"></a>6.泛型</h1><p>软件工程中，我们不仅要创建定义良好且一致的 API，同时也要考虑可重用性。 组件不仅能够支持当前的数据类型，同时也能支持未来的数据类型，这在创建大型系统时为你提供了十分灵活的功能。</p>
<p>在像 C# 和 Java 这样的语言中，可以使用泛型来创建可重用的组件，一个组件可以支持多种类型的数据。 这样用户就可以以自己的数据类型来使用组件。</p>
<h2 id="6-1-泛型基础示例"><a href="#6-1-泛型基础示例" class="headerlink" title="6.1 泛型基础示例"></a>6.1 泛型基础示例</h2><p>下面来创建第一个使用泛型的例子：<code>identity</code> 函数。 这个函数会返回任何传入它的值。 你可以把这个函数当成是 <code>echo</code> 命令。</p>
<p>不用泛型的话，这个函数可能是下面这样：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">identity</span>(<span class="params">arg: <span class="built_in">number</span></span>): <span class="title">number</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>或者，我们使用 <code>any</code> 类型来定义函数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">identity</span>(<span class="params">arg: <span class="built_in">any</span></span>): <span class="title">any</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>使用 <code>any</code> 类型会导致这个函数可以接收任何类型的 <code>arg</code> 参数，但是这样就丢失了一些信息：传入的类型与返回的类型应该是相同的。如果我们传入一个数字，我们只知道任何类型的值都有可能被返回。</p>
<p>因此，我们需要一种方法使返回值的类型与传入参数的类型是相同的。这里，我们使用了<em>类型变量</em>，它是一种特殊的变量，只用于表示类型而不是值。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">identity</span>&lt;<span class="title">T</span>&gt;(<span class="params">arg: T</span>): <span class="title">T</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们给 <code>identity</code> 添加了类型变量 <code>T</code>。 <code>T</code> 帮助我们捕获用户传入的类型（比如：<code>number</code>），之后我们就可以使用这个类型。 之后我们再次使用了 <code>T</code> 当做返回值类型。现在我们可以知道参数类型与返回值类型是相同的了。这允许我们跟踪函数里使用的类型的信息。</p>
<p>我们把这个版本的 <code>identity</code> 函数叫做泛型，因为它可以适用于多个类型。 不同于使用 <code>any</code>，它不会丢失信息，像第一个例子那像保持准确性，传入数值类型并返回数值类型。</p>
<p>我们定义了泛型函数后，可以用两种方法使用。 第一种是，传入所有的参数，包含类型参数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> output = identity&lt;<span class="built_in">string</span>&gt;(<span class="string">&#x27;myString&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>这里我们明确的指定了 <code>T</code> 是 <code>string</code> 类型，并做为一个参数传给函数，使用了 <code>&lt;&gt;</code> 括起来而不是 <code>()</code>。</p>
<p>第二种方法更普遍。利用了<em>类型推论</em> – 即编译器会根据传入的参数自动地帮助我们确定 <code>T</code> 的类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> output = identity(<span class="string">&#x27;myString&#x27;</span>);</span><br></pre></td></tr></table></figure>

<p>注意我们没必要使用尖括号（<code>&lt;&gt;</code>）来明确地传入类型；编译器可以查看 <code>myString</code> 的值，然后把 <code>T</code> 设置为它的类型。 类型推论帮助我们保持代码精简和高可读性。如果编译器不能够自动地推断出类型的话，只能像上面那样明确的传入 <code>T</code> 的类型，在一些复杂的情况下，这是可能出现的。</p>
<h2 id="6-2-使用泛型变量"><a href="#6-2-使用泛型变量" class="headerlink" title="6.2 使用泛型变量"></a>6.2 使用泛型变量</h2><p>使用泛型创建像 <code>identity</code> 这样的泛型函数时，编译器要求你在函数体必须正确的使用这个通用的类型。 换句话说，你必须把这些参数当做是任意或所有类型。</p>
<p>看下之前 <code>identity</code> 例子：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">identity</span>&lt;<span class="title">T</span>&gt;(<span class="params">arg: T</span>): <span class="title">T</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果我们想打印出 <code>arg</code> 的长度。 我们很可能会这样做：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">loggingIdentity</span>&lt;<span class="title">T</span>&gt;(<span class="params">arg: T</span>): <span class="title">T</span> </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(arg.length);</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果这么做，编译器会报错说我们使用了 <code>arg</code> 的 <code>.length</code> 属性，但是没有地方指明 <code>arg</code> 具有这个属性。记住，这些类型变量代表的是任意类型，所以使用这个函数的人可能传入的是个数字，而数字是没有 <code>.length</code> 属性的。</p>
<p>现在假设我们想操作 <code>T</code> 类型的数组而不直接是 <code>T</code>。由于我们操作的是数组，所以 <code>.length</code> 属性是应该存在的。我们可以像创建其它数组一样创建这个数组：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">loggingIdentity</span>&lt;<span class="title">T</span>&gt;(<span class="params">arg: T[]</span>): <span class="title">T</span>[] </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(arg.length);</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>你可以这样理解 <code>loggingIdentity</code> 的类型：泛型函数 <code>loggingIdentity</code>，接收类型参数 <code>T</code> 和参数 <code>arg</code>，它是个元素类型是 <code>T</code> 的数组，并返回元素类型是<code>T</code> 的数组。 如果我们传入数字数组，将返回一个数字数组，因为此时 <code>T</code> 的的类型为 <code>number</code>。 这可以让我们把泛型变量 <code>T</code> 当做类型的一部分使用，而不是整个类型，增加了灵活性。</p>
<h2 id="6-3-泛型类型"><a href="#6-3-泛型类型" class="headerlink" title="6.3 泛型类型"></a>6.3 泛型类型</h2><p>上一节，创建的 <code>identity</code> 通用函数，可以适用于不同的类型。 在这节种研究一下函数本身的类型，以及如何创建泛型接口。</p>
<p>泛型函数的类型与非泛型函数的类型没什么不同，只是有一个类型参数在最前面，像函数声明一样：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">identity</span>&lt;<span class="title">T</span>&gt;(<span class="params">arg: T</span>): <span class="title">T</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myIdentity: &lt;T&gt;<span class="function">(<span class="params">arg: T</span>) =&gt;</span> T = identity;</span><br></pre></td></tr></table></figure>

<p>我们也可以使用不同的泛型参数名，只要在数量上和使用方式上能对应上就可以。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">identity</span>&lt;<span class="title">T</span>&gt;(<span class="params">arg: T</span>): <span class="title">T</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myIdentity: &lt;U&gt;<span class="function">(<span class="params">arg: U</span>) =&gt;</span> U = identity;</span><br></pre></td></tr></table></figure>

<p>我们还可以使用带有调用签名的对象字面量来定义泛型函数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">identity</span>&lt;<span class="title">T</span>&gt;(<span class="params">arg: T</span>): <span class="title">T</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myIdentity: &#123;</span><br><span class="line">    &lt;T&gt;(arg: T): T</span><br><span class="line">&#125; = identity;</span><br></pre></td></tr></table></figure>

<p>这引导我们去写第一个泛型接口了。我们把上面例子里的对象字面量拿出来做为一个接口：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> GenericIdentityFn &#123;</span><br><span class="line">    &lt;T&gt;(arg: T): T;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">identity</span>&lt;<span class="title">T</span>&gt;(<span class="params">arg: T</span>): <span class="title">T</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myIdentity: GenericIdentityFn = identity;</span><br></pre></td></tr></table></figure>

<p>我们甚至可以把泛型参数当作整个接口的一个参数。 这样我们就能清楚的知道使用的具体是哪个泛型类型（比如： <code>Dictionary&lt;string&gt;</code> 而不只是<code>Dictionary</code>）。这样接口里的其它成员也能知道这个参数的类型了。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> GenericIdentityFn&lt;T&gt; &#123;</span><br><span class="line">    (arg: T): T;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">identity</span>&lt;<span class="title">T</span>&gt;(<span class="params">arg: T</span>): <span class="title">T</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myIdentity: GenericIdentityFn&lt;<span class="built_in">number</span>&gt; = identity;</span><br></pre></td></tr></table></figure>

<p>注意，我们的示例做了少许改动。 不再描述泛型函数，而是把非泛型函数签名作为泛型类型一部分。 当我们使用 <code>GenericIdentityFn</code> 的时候，还得传入一个类型参数来指定泛型类型（这里是：<code>number</code>），锁定了之后代码里使用的类型。对于描述哪部分类型属于泛型部分来说，理解何时把参数放在调用签名里和何时放在接口上是很有帮助的。</p>
<p>除了泛型接口，我们还可以创建泛型类。 注意，无法创建泛型枚举和泛型命名空间。</p>
<h2 id="6-4-泛型类"><a href="#6-4-泛型类" class="headerlink" title="6.4 泛型类"></a>6.4 泛型类</h2><p>泛型类看上去与泛型接口差不多。 泛型类使用（ <code>&lt;&gt;</code>）括起泛型类型，跟在类名后面。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GenericNumber</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    zeroValue: T</span><br><span class="line">    add: <span class="function">(<span class="params">x: T, y: T</span>) =&gt;</span> T</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> myGenericNumber = <span class="keyword">new</span> GenericNumber&lt;<span class="built_in">number</span>&gt;();</span><br><span class="line">myGenericNumber.zeroValue = <span class="number">0</span>;</span><br><span class="line">myGenericNumber.add = <span class="function"><span class="keyword">function</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>GenericNumber</code> 类的使用是十分直观的，并且你可能已经注意到了，没有什么去限制它只能使用 <code>number</code> 类型。 也可以使用字符串或其它更复杂的类型。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> stringNumeric = <span class="keyword">new</span> GenericNumber&lt;<span class="built_in">string</span>&gt;()</span><br><span class="line">stringNumeric.zeroValue = <span class="string">&#x27;&#x27;</span></span><br><span class="line">stringNumeric.add = <span class="function"><span class="keyword">function</span>(<span class="params">x, y</span>) </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(stringNumeric.add(stringNumeric.zeroValue, <span class="string">&#x27;test&#x27;</span>)); <span class="comment">// script.ts(1,25): error TS2304: Cannot find name &#x27;GenericNumber&#x27;.</span></span><br></pre></td></tr></table></figure>

<p>与接口一样，直接把泛型类型放在类后面，可以帮助我们确认类的所有属性都在使用相同的类型。</p>
<p>我们在类那节说过，类有两部分：静态部分和实例部分。 泛型类指的是实例部分的类型，所以类的静态属性不能使用这个泛型类型。</p>
<h2 id="6-5-泛型约束"><a href="#6-5-泛型约束" class="headerlink" title="6.5 泛型约束"></a>6.5 泛型约束</h2><p>我们有时候想操作某类型的一组值，并且我们知道这组值具有什么样的属性。在 <code>loggingIdentity</code> 例子中，我们想访问 <code>arg</code> 的 <code>length</code> 属性，但是编译器并不能证明每种类型都有 <code>length</code> 属性，所以就报错了。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">loggingIdentity</span>&lt;<span class="title">T</span>&gt;(<span class="params">arg: T</span>): <span class="title">T</span> </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(arg.length);</span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>相比于操作 <code>any</code> 所有类型，我们想要限制函数去处理任意带有 <code>.length</code> 属性的所有类型。 只要传入的类型有这个属性，我们就允许，就是说至少包含这一属性。为此，我们需要列出对于 <code>T</code> 的约束要求。</p>
<p>我们定义一个接口来描述约束条件，创建一个包含 <code>.length</code> 属性的接口，使用这个接口和 <code>extends</code> 关键字来实现约束：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Lengthwise &#123;</span><br><span class="line">    length: <span class="built_in">number</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">loggingIdentity</span>&lt;<span class="title">T</span> <span class="title">extends</span> <span class="title">Lengthwise</span>&gt;(<span class="params">arg: T</span>): <span class="title">T</span> </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(arg.length) <span class="comment">// OK</span></span><br><span class="line">    <span class="keyword">return</span> arg;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>现在这个泛型函数被定义了约束，因此它不再是适用于任意类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">loggingIdentity(<span class="number">3</span>);  <span class="comment">// Error</span></span><br></pre></td></tr></table></figure>

<p>我们需要传入符合约束类型的值，必须包含必须的属性：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">loggingIdentity(&#123;</span><br><span class="line">    length: <span class="number">10</span>,</span><br><span class="line">    value: <span class="number">3</span></span><br><span class="line">&#125;); <span class="comment">// OK</span></span><br></pre></td></tr></table></figure>

<h3 id="6-5-1-在泛型约束中使用类型参数"><a href="#6-5-1-在泛型约束中使用类型参数" class="headerlink" title="6.5.1 在泛型约束中使用类型参数"></a>6.5.1 在泛型约束中使用类型参数</h3><p>你可以声明一个类型参数，且它被另一个类型参数所约束。 比如，现在我们想要用属性名从对象里获取这个属性。 并且我们想要确保这个属性存在于对象 <code>obj</code> 上，因此我们需要在这两个类型之间使用约束。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getProperty</span>&lt;<span class="title">T</span>, <span class="title">K</span> <span class="title">extends</span> <span class="title">keyof</span> <span class="title">T</span>&gt; (<span class="params">obj: T, key: K </span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> obj[key];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> x = &#123;</span><br><span class="line">    a: <span class="number">1</span>,</span><br><span class="line">    b: <span class="number">2</span>,</span><br><span class="line">    c: <span class="number">3</span>,</span><br><span class="line">    d: <span class="number">4</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">getProperty(x, <span class="string">&#x27;a&#x27;</span>); <span class="comment">// okay</span></span><br><span class="line">getProperty(x, <span class="string">&#x27;m&#x27;</span>); <span class="comment">// error</span></span><br></pre></td></tr></table></figure>

<h1 id="7-类型推断"><a href="#7-类型推断" class="headerlink" title="7.类型推断"></a>7.类型推断</h1><h2 id="7-1-类型推断基础"><a href="#7-1-类型推断基础" class="headerlink" title="7.1 类型推断基础"></a>7.1 类型推断基础</h2><p>TypeScript 里，在有些没有明确指出类型的地方，类型推断会帮助提供类型。如下面的例子：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> x = <span class="number">3</span>;</span><br></pre></td></tr></table></figure>

<p>变量 <code>x</code> 的类型被推断为数字。 这种推断发生在初始化变量和成员，设置默认参数值和决定函数返回值时。</p>
<p>大多数情况下，类型推断是直截了当地。后面的小节，我们会浏览类型推断时的细微差别。</p>
<h2 id="7-2-最佳通用类型"><a href="#7-2-最佳通用类型" class="headerlink" title="7.2 最佳通用类型"></a>7.2 最佳通用类型</h2><p>有些时候我们需要从几个表达式中推断类型，会使用这些表达式的类型来推断出一个最合适的通用类型。例如，</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> x = [<span class="number">0</span>, <span class="number">1</span>, <span class="literal">null</span>];</span><br></pre></td></tr></table></figure>

<p>为了推断 <code>x</code> 的类型，我们必须考虑所有元素的类型。 这里有两种选择：<code>number</code> 和 <code>null</code>。 计算通用类型算法会考虑所有的候选类型，并给出一个兼容所有候选类型的类型。</p>
<p>由于最终的通用类型取自候选类型，有些时候候选类型共享一个公共结构，但是却没有一个类型能做为所有候选类型的超级类型。例如：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    numLegs: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bee</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Lion</span> <span class="keyword">extends</span> <span class="title">Animal</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> zoo = [</span><br><span class="line">    <span class="keyword">new</span> Bee(),</span><br><span class="line">    <span class="keyword">new</span> Lion()</span><br><span class="line">];</span><br></pre></td></tr></table></figure>

<p>这里，我们想让 <code>zoo</code> 被推断为 <code>Animal[]</code> 类型，但是这个数组里没有对象是 <code>Animal</code> 类型的，因此不能推断出这个结果。 为了更正，我们可以明确的声明我们期望的类型：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> zoo: Animal[] = [</span><br><span class="line">    <span class="keyword">new</span> Bee(),</span><br><span class="line">    <span class="keyword">new</span> Lion()</span><br><span class="line">];</span><br></pre></td></tr></table></figure>

<p>如果没有找到最佳通用类型的话，类型推断的结果为联合数组类型，<code>(Bee | Lion)[]</code></p>
<h2 id="7-3-上下文类型"><a href="#7-3-上下文类型" class="headerlink" title="7.3 上下文类型"></a>7.3 上下文类型</h2><p>有些时候，TypeScript 类型推断会按另外一种方式，我们称作“上下文类型”；上下文类型的出现和表达式的类型以及所处的位置相关。比如：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onmousedown = <span class="function"><span class="keyword">function</span>(<span class="params">mouseEvent</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(mouseEvent.clickTime);  <span class="comment">// Error</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个例子会得到一个类型错误，TypeScript 类型检查器使用 <code>window.onmousedown</code> 函数的类型来推断右边函数表达式的类型。 因此，就能推断出 <code>mouseEvent</code> 参数的类型了，所以 <code>mouseEvent</code> 访问了一个不存在的属性，就报错了。</p>
<p>如果上下文类型表达式包含了明确的类型信息，上下文的类型被忽略。重写上面的例子：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onmousedown = <span class="function"><span class="keyword">function</span>(<span class="params">mouseEvent:<span class="built_in">any</span></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(mouseEvent.clickTime)  <span class="comment">// OK</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个函数表达式有明确的参数类型注解，上下文类型被忽略。这样的话就不报错了，因为这里不会使用到上下文类型。</p>
<p>上下文类型会在很多情况下使用到。通常包含函数的参数，赋值表达式的右边，类型断言，对象成员，数组字面量和返回值语句。上下文类型也会做为最佳通用类型的候选类型。比如：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createZoo</span>(<span class="params"></span>): <span class="title">Animal</span>[] </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> [<span class="keyword">new</span> Bee(), <span class="keyword">new</span> Lion()];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> zoo = createZoo();</span><br></pre></td></tr></table></figure>

<p>这个例子里，最佳通用类型有 <code>3</code> 个候选者：<code>Animal</code>，<code>Bee</code> 和 <code>Lion</code>。 其中，<code>Animal</code> 会被做为最佳通用类型。</p>
<h1 id="8-高级类型"><a href="#8-高级类型" class="headerlink" title="8.高级类型"></a>8.高级类型</h1><h2 id="8-1-交叉类型"><a href="#8-1-交叉类型" class="headerlink" title="8.1 交叉类型"></a>8.1 交叉类型</h2><p>交叉类型是将多个类型合并为一个类型。 这让我们可以把现有的多种类型叠加到一起成为一种类型，它包含了所需的所有类型的特性。 例如，<code>Person &amp; Loggable</code> 同时是 <code>Person</code> 和 <code>Loggable</code>。 就是说这个类型的对象同时拥有了这两种类型的成员。</p>
<p>我们大多是在混入（mixins）或其它不适合典型面向对象模型的地方看到交叉类型的使用。 （在 JavaScript 里发生这种情况的场合很多！） 下面是如何创建混入的一个简单例子：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">extend</span>&lt;<span class="title">T</span>, <span class="title">U</span>&gt; (<span class="params">first: T, second: U</span>): <span class="title">T</span> &amp; <span class="title">U</span> </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> result = &#123;&#125; <span class="keyword">as</span> T &amp; U;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> id <span class="keyword">in</span> first) &#123;</span><br><span class="line">        result[id] = first[id] <span class="keyword">as</span> <span class="built_in">any</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> id <span class="keyword">in</span> second) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!result.hasOwnProperty(id)) &#123;</span><br><span class="line">            result[id] = second[id] <span class="keyword">as</span> <span class="built_in">any</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span> </span>&#123;</span><br><span class="line">    <span class="title">constructor</span> (<span class="params"><span class="keyword">public</span> name: <span class="built_in">string</span></span>) &#123;</span><br><span class="line">        </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> Loggable &#123;</span><br><span class="line">    log (): <span class="built_in">void</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ConsoleLogger</span> <span class="title">implements</span> <span class="title">Loggable</span> </span>&#123;</span><br><span class="line">    log () &#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> jim = extend(<span class="keyword">new</span> Person(<span class="string">&#x27;Jim&#x27;</span>), <span class="keyword">new</span> ConsoleLogger());</span><br><span class="line"><span class="keyword">var</span> n = jim.name;</span><br><span class="line">jim.log()</span><br></pre></td></tr></table></figure>

<h2 id="8-2-联合类型"><a href="#8-2-联合类型" class="headerlink" title="8.2 联合类型"></a>8.2 联合类型</h2><p>联合类型与交叉类型很有关联，但是使用上却完全不同。 偶尔你会遇到这种情况，一个代码库希望传入 <code>number</code> 或 <code>string</code> 类型的参数。 例如下面的函数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">padLeft</span>(<span class="params">value: <span class="built_in">string</span>, padding: <span class="built_in">any</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> padding === <span class="string">&#x27;number&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Array</span>(padding + <span class="number">1</span>).join(<span class="string">&#x27; &#x27;</span>) + value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> padding === <span class="string">&#x27;string&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> padding + value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">`Expected string or number, got &#x27;<span class="subst">$&#123;padding&#125;</span>&#x27;.`</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">padLeft(<span class="string">&#x27;Hello world&#x27;</span>, <span class="number">4</span>) <span class="comment">// returns &quot;    Hello world&quot;</span></span><br></pre></td></tr></table></figure>

<p><code>padLeft</code> 存在一个问题，<code>padding</code> 参数的类型指定成了 <code>any</code>。 这就是说我们可以传入一个既不是 <code>number</code> 也不是 <code>string</code> 类型的参数，但是 TypeScript 却不报错。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> indentedString = padLeft(<span class="string">&#x27;Hello world&#x27;</span>, <span class="literal">true</span>); <span class="comment">// 编译阶段通过，运行时报错</span></span><br></pre></td></tr></table></figure>

<p>为了解决这个问题，我们可以使用 联合类型做为 <code>padding</code> 的参数：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">padLeft</span>(<span class="params">value: <span class="built_in">string</span>, padding: <span class="built_in">string</span> | <span class="built_in">number</span></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> indentedString = padLeft(<span class="string">&#x27;Hello world&#x27;</span>, <span class="literal">true</span>); <span class="comment">// 编译阶段报错</span></span><br></pre></td></tr></table></figure>

<p>联合类型表示一个值可以是几种类型之一。我们用竖线（<code>|</code>）分隔每个类型，所以 <code>number | string</code> 表示一个值可以是 <code>number</code> 或 <code>string</code>。</p>
<p>如果一个值是联合类型，我们只能访问此联合类型的所有类型里共有的成员。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> Bird &#123;</span><br><span class="line">    fly();</span><br><span class="line">    layEggs();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> Fish &#123;</span><br><span class="line">    swim();</span><br><span class="line">    layEggs();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getSmallPet</span>(<span class="params"></span>): <span class="title">Fish</span> | <span class="title">Bird</span> </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> pet = getSmallPet();</span><br><span class="line">pet.layEggs(); <span class="comment">// okay</span></span><br><span class="line">pet.swim(); <span class="comment">// error</span></span><br></pre></td></tr></table></figure>

<p>这里的联合类型可能有点复杂：如果一个值的类型是 <code>A | B</code>，我们能够确定的是它包含了 <code>A</code> 和 <code>B</code> 中共有的成员。这个例子里，<code>Fish</code> 具有一个 <code>swim</code> 方法，我们不能确定一个 <code>Bird | Fish</code> 类型的变量是否有 <code>swim</code>方法。 如果变量在运行时是 <code>Bird</code> 类型，那么调用 <code>pet.swim()</code> 就出错了。</p>
<h2 id="8-3-类型保护"><a href="#8-3-类型保护" class="headerlink" title="8.3 类型保护"></a>8.3 类型保护</h2><p>联合类型适合于那些值可以为不同类型的情况。 但当我们想确切地了解是否为 <code>Fish</code> 或者是 <code>Bird</code> 时怎么办？ JavaScript 里常用来区分这 2 个可能值的方法是检查成员是否存在。如之前提及的，我们只能访问联合类型中共同拥有的成员。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> pet = getSmallPet();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 每一个成员访问都会报错</span></span><br><span class="line"><span class="keyword">if</span> (pet.swim) &#123;</span><br><span class="line">    pet.swim();</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (pet.fly) &#123;</span><br><span class="line">    pet.fly();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>为了让这段代码工作，我们要使用类型断言：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> pet = getSmallPet();</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> ((pet <span class="keyword">as</span> Fish).swim) &#123;</span><br><span class="line">    (pet <span class="keyword">as</span> Fish).swim();</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    (pet <span class="keyword">as</span> Bird).fly();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="8-3-1-用户自定义的类型保护"><a href="#8-3-1-用户自定义的类型保护" class="headerlink" title="8.3.1 用户自定义的类型保护"></a>8.3.1 用户自定义的类型保护</h3><p>这里可以注意到我们不得不多次使用类型断言。如果我们一旦检查过类型，就能在之后的每个分支里清楚地知道 <code>pet</code> 的类型的话就好了。</p>
<p>TypeScript 里的<em>类型保护</em>机制让它成为了现实。 类型保护就是一些表达式，它们会在运行时检查以确保在某个作用域里的类型。定义一个类型保护，我们只要简单地定义一个函数，它的返回值是一个<em>类型谓词</em>：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isFish</span>(<span class="params">pet: Fish | Bird</span>): <span class="title">pet</span> <span class="title">is</span> <span class="title">Fish</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (pet <span class="keyword">as</span> Fish).swim !== <span class="literal">undefined</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在这个例子里，<code>pet is Fish</code> 就是类型谓词。谓词为 <code>parameterName is Type</code> 这种形式， <code>parameterName</code> 必须是来自于当前函数签名里的一个参数名。</p>
<p>每当使用一些变量调用 <code>isFish</code> 时，<code>TypeScript</code> 会将变量缩减为那个具体的类型。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (isFish(pet)) &#123;</span><br><span class="line">    pet.swim();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span> &#123;</span><br><span class="line">    pet.fly();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意 <code>TypeScript</code> 不仅知道在 <code>if</code> 分支里 <code>pet</code> 是 <code>Fish</code> 类型；它还清楚在 <code>else</code> 分支里，一定不是 Fish类型而是 <code>Bird</code> 类型。</p>
<h3 id="8-3-2-typeof-类型保护"><a href="#8-3-2-typeof-类型保护" class="headerlink" title="8.3.2 typeof 类型保护"></a>8.3.2 typeof 类型保护</h3><p>现在我们回过头来看看怎么使用联合类型书写 <code>padLeft</code> 代码。我们可以像下面这样利用类型断言来写：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isNumber</span> (<span class="params">x: <span class="built_in">any</span></span>):<span class="title">x</span> <span class="title">is</span> <span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">typeof</span> x === <span class="string">&#x27;number&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isString</span> (<span class="params">x: <span class="built_in">any</span></span>): <span class="title">x</span> <span class="title">is</span> <span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">typeof</span> x === <span class="string">&#x27;string&#x27;</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">padLeft</span> (<span class="params">value: <span class="built_in">string</span>, padding: <span class="built_in">string</span> | <span class="built_in">number</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (isNumber(padding)) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Array</span>(padding + <span class="number">1</span>).join(<span class="string">&#x27; &#x27;</span>) + value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (isString(padding)) &#123;</span><br><span class="line">        <span class="keyword">return</span> padding + value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">`Expected string or number, got &#x27;<span class="subst">$&#123;padding&#125;</span>&#x27;.`</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然而，你必须要定义一个函数来判断类型是否是原始类型，但这并不必要。其实我们不必将 <code>typeof x === &#39;number&#39;</code>抽象成一个函数，因为 TypeScript 可以将它识别为一个类型保护。 也就是说我们可以直接在代码里检查类型了。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">padLeft</span> (<span class="params">value: <span class="built_in">string</span>, padding: <span class="built_in">string</span> | <span class="built_in">number</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> padding === <span class="string">&#x27;number&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Array</span>(padding + <span class="number">1</span>).join(<span class="string">&#x27; &#x27;</span>) + value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> padding === <span class="string">&#x27;string&#x27;</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> padding + value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">`Expected string or number, got &#x27;<span class="subst">$&#123;padding&#125;</span>&#x27;.`</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这些 <code>typeof</code> 类型保护只有两种形式能被识别：<code>typeof v === &quot;typename&quot;</code> 和 <code>typeof v !== &quot;typename&quot;</code>， <code>&quot;typename&quot;</code>必须是 <code>&quot;number&quot;</code>， <code>&quot;string&quot;</code>，<code>&quot;boolean&quot;</code> 或 <code>&quot;symbol&quot;</code>。 但是 TypeScript 并不会阻止你与其它字符串比较，只是 TypeScript 不会把那些表达式识别为类型保护。</p>
<h3 id="8-3-3-instanceof-类型保护"><a href="#8-3-3-instanceof-类型保护" class="headerlink" title="8.3.3 instanceof 类型保护"></a>8.3.3 instanceof 类型保护</h3><p>如果你已经阅读了 <code>typeof</code> 类型保护并且对 JavaScript 里的 <code>instanceof</code> 操作符熟悉的话，你可能已经猜到了这节要讲的内容。</p>
<p><code>instanceof</code> 类型保护是通过构造函数来细化类型的一种方式。我们把之前的例子做一个小小的改造：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Bird</span> </span>&#123;</span><br><span class="line">    fly () &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;bird fly&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    layEggs () &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;bird lay eggs&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Fish</span> </span>&#123;</span><br><span class="line">    swim () &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;fish swim&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    layEggs () &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">&#x27;fish lay eggs&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getRandomPet</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Math</span>.random() &gt; <span class="number">0.5</span> ? <span class="keyword">new</span> Bird() : <span class="keyword">new</span> Fish();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> pet = getRandomPet();</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (pet <span class="keyword">instanceof</span> Bird) &#123;</span><br><span class="line">    pet.fly();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> (pet <span class="keyword">instanceof</span> Fish) &#123;</span><br><span class="line">    pet.swim();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="8-4-可以为-null-的类型"><a href="#8-4-可以为-null-的类型" class="headerlink" title="8.4 可以为 null 的类型"></a>8.4 可以为 null 的类型</h2><p>TypeScript 具有两种特殊的类型，<code>null</code> 和 <code>undefined</code>，它们分别具有值 <code>null</code> 和 <code>undefined</code>。我们在基础类型一节里已经做过简要说明。 默认情况下，类型检查器认为 <code>null</code> 与 <code>undefined</code> 可以赋值给任何类型。 <code>null</code> 与 <code>undefined</code> 是所有其它类型的一个有效值。 这也意味着，你阻止不了将它们赋值给其它类型，就算是你想要阻止这种情况也不行。<code>null</code>的发明者，Tony Hoare，称它为价值亿万美金的错误 (opens new window)。</p>
<p><code>--strictNullChecks</code> 标记可以解决此错误：当你声明一个变量时，它不会自动地包含 <code>null</code> 或 <code>undefined</code>。 你可以使用联合类型明确的包含它们：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> s = <span class="string">&#x27;foo&#x27;</span>;</span><br><span class="line">s = <span class="literal">null</span>; <span class="comment">// 错误, &#x27;null&#x27;不能赋值给&#x27;string&#x27;</span></span><br><span class="line"><span class="keyword">let</span> sn: <span class="built_in">string</span> | <span class="literal">null</span> = <span class="string">&#x27;bar&#x27;</span>;</span><br><span class="line">sn = <span class="literal">null</span>; <span class="comment">// 可以</span></span><br><span class="line"></span><br><span class="line">sn = <span class="literal">undefined</span>; <span class="comment">// error, &#x27;undefined&#x27;不能赋值给&#x27;string | null&#x27;</span></span><br></pre></td></tr></table></figure>

<p>注意，按照 JavaScript 的语义，TypeScript 会把 <code>null</code> 和 <code>undefined</code> 区别对待。<code>string | null</code>，<code>string | undefined</code> 和 <code>string | undefined | null</code> 是不同的类型。</p>
<h3 id="8-4-1-可选参数和可选属性"><a href="#8-4-1-可选参数和可选属性" class="headerlink" title="8.4.1 可选参数和可选属性"></a>8.4.1 可选参数和可选属性</h3><p>使用了 <code>--strictNullChecks</code>，可选参数会被自动地加上 <code>| undefined</code>:</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params">x: <span class="built_in">number</span>, y?: <span class="built_in">number</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> x + (y || <span class="number">0</span>);</span><br><span class="line">&#125;</span><br><span class="line">f(<span class="number">1</span>, <span class="number">2</span>);</span><br><span class="line">f(<span class="number">1</span>);</span><br><span class="line">f(<span class="number">1</span>, <span class="literal">undefined</span>);</span><br><span class="line">f(<span class="number">1</span>, <span class="literal">null</span>); <span class="comment">// error, &#x27;null&#x27; 不能赋值给 &#x27;number | undefined&#x27;</span></span><br></pre></td></tr></table></figure>

<p>可选属性也会有同样的处理：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">C</span> </span>&#123;</span><br><span class="line">    a: <span class="built_in">number</span>,</span><br><span class="line">    b?: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> c = <span class="keyword">new</span> C();</span><br><span class="line">c.a = <span class="number">12</span>;</span><br><span class="line">c.a = <span class="literal">undefined</span>; <span class="comment">// error, &#x27;undefined&#x27; 不能赋值给 &#x27;number&#x27;</span></span><br><span class="line">c.b = <span class="number">13</span>;</span><br><span class="line">c.b = <span class="literal">undefined</span>; <span class="comment">// ok</span></span><br><span class="line">c.b = <span class="literal">null</span>; <span class="comment">// error, &#x27;null&#x27; 不能赋值给 &#x27;number | undefined&#x27;</span></span><br></pre></td></tr></table></figure>

<h3 id="8-4-2-类型保护和类型断言"><a href="#8-4-2-类型保护和类型断言" class="headerlink" title="8.4.2 类型保护和类型断言"></a>8.4.2 类型保护和类型断言</h3><p>由于可以为 <code>null</code> 的类型能和其它类型定义为联合类型，那么你需要使用类型保护来去除 <code>null</code>。幸运地是这与在 <code>JavaScript</code> 里写的代码一致：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params">sn: <span class="built_in">string</span> | <span class="literal">null</span></span>): <span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (sn === <span class="literal">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&#x27;default&#x27;</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> sn;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里很明显地去除了 <code>null</code>，你也可以使用短路运算符：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params">sn: <span class="built_in">string</span> | <span class="literal">null</span></span>): <span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> sn || <span class="string">&#x27;default&#x27;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果编译器不能够去除 <code>null</code> 或 <code>undefined</code>，你可以使用类型断言手动去除。语法是添加 <code>!</code> 后缀： <code>identifier!</code> 从 <code>identifier</code> 的类型里去除了 <code>null</code> 和 <code>undefined</code>：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">broken</span>(<span class="params">name: <span class="built_in">string</span> | <span class="literal">null</span></span>): <span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">postfix</span>(<span class="params">epithet: <span class="built_in">string</span></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name.charAt(<span class="number">0</span>) + <span class="string">&#x27;.  the &#x27;</span> + epithet; <span class="comment">// error, &#x27;name&#x27; 可能为 null</span></span><br><span class="line">    &#125;</span><br><span class="line">    name = name || <span class="string">&#x27;Bob&#x27;</span>;</span><br><span class="line">    <span class="keyword">return</span> postfix(<span class="string">&#x27;great&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fixed</span>(<span class="params">name: <span class="built_in">string</span> | <span class="literal">null</span></span>): <span class="title">string</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">postfix</span>(<span class="params">epithet: <span class="built_in">string</span></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name!.charAt(<span class="number">0</span>) + <span class="string">&#x27;.  the &#x27;</span> + epithet; <span class="comment">// ok</span></span><br><span class="line">    &#125;</span><br><span class="line">    name = name || <span class="string">&#x27;Bob&#x27;</span>;</span><br><span class="line">    <span class="keyword">return</span> postfix(<span class="string">&#x27;great&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">broken(<span class="literal">null</span>);</span><br></pre></td></tr></table></figure>

<p>本例使用了嵌套函数，因为编译器无法去除嵌套函数的 <code>null</code>（除非是立即调用的函数表达式）。因为它无法跟踪所有对嵌套函数的调用，尤其是你将内层函数做为外层函数的返回值。如果无法知道函数在哪里被调用，就无法知道调用时 <code>name</code> 的类型。</p>
<h2 id="8-5-字符串字面量类型"><a href="#8-5-字符串字面量类型" class="headerlink" title="8.5 字符串字面量类型"></a>8.5 字符串字面量类型</h2><p>字符串字面量类型允许你指定字符串必须具有的确切值。在实际应用中，字符串字面量类型可以与联合类型，类型保护很好的配合。通过结合使用这些特性，你可以实现类似枚举类型的字符串。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> Easing = <span class="string">&#x27;ease-in&#x27;</span> | <span class="string">&#x27;ease-out&#x27;</span> | <span class="string">&#x27;ease-in-out&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UIElement</span> </span>&#123;</span><br><span class="line">    animate (dx: <span class="built_in">number</span>, <span class="attr">dy</span>: <span class="built_in">number</span>, <span class="attr">easing</span>: Easing) &#123;</span><br><span class="line">        <span class="keyword">if</span> (easing === <span class="string">&#x27;ease-in&#x27;</span>) &#123;</span><br><span class="line">            <span class="comment">// ...</span></span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (easing === <span class="string">&#x27;ease-out&#x27;</span>) &#123;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (easing === <span class="string">&#x27;ease-in-out&#x27;</span>) &#123;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// error! 不能传入 null 或者 undefined.</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> button = <span class="keyword">new</span> UIElement();</span><br><span class="line">button.animate(<span class="number">0</span>, <span class="number">0</span>, <span class="string">&#x27;ease-in&#x27;</span>);</span><br><span class="line">button.animate(<span class="number">0</span>, <span class="number">0</span>, <span class="string">&#x27;uneasy&#x27;</span>); <span class="comment">// error</span></span><br></pre></td></tr></table></figure>

<p>你只能从三种允许的字符中选择其一来做为参数传递，传入其它值则会产生错误。</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Argument of type &#x27;&quot;uneasy&quot;&#x27; is not assignable to parameter of type &#x27;&quot;ease-in&quot; | &quot;ease-out&quot; | &quot;ease-in-out&quot;&#x27;</span><br></pre></td></tr></table></figure>

<h2 id="8-6-总结"><a href="#8-6-总结" class="headerlink" title="8.6 总结"></a>8.6 总结</h2><p>那么到这里，我们的 TypeScript 常用语法学习就告一段落了，当然 TypeScript 还有其他的语法我们并没有讲，我们只是讲了 TypeScript 的一些常用语法，你们把这些知识学会已经足以开发一般的应用了。如果你在使用 TypeScript 开发项目中遇到了其他的 TypeScript 语法知识，你可以通过 TypeScript 的<a target="_blank" rel="noopener" href="https://www.typescriptlang.org/docs/home.html">官网文档 (opens new window)</a>学习。因为学基础最好的方法还是去阅读它的官网文档，敲上面的小例子。其实我们课程的基础知识结构也是大部分参考了官网文档，要记住学习一门技术的基础官网文档永远是最好的第一手资料。</p>

    </div>

    
    
    
      
<div>
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
</div>
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JavaScript/" rel="tag"><i class="fa fa-tag"></i> JavaScript</a>
              <a href="/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/" rel="tag"><i class="fa fa-tag"></i> 编程语言</a>
              <a href="/tags/Typescript/" rel="tag"><i class="fa fa-tag"></i> Typescript</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/04/05/JavaScript%E7%B1%BB%E5%9E%8B%E8%BD%AC%E6%8D%A2/" rel="prev" title="JavaScript类型转换">
      <i class="fa fa-chevron-left"></i> JavaScript类型转换
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/04/08/%E6%89%8B%E5%86%99%E4%B8%80%E4%B8%AA%E8%AE%A1%E7%AE%97%E5%99%A8/" rel="next" title="手写一个计算器">
      手写一个计算器 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-%E5%88%9D%E8%AF%86-TypeScript"><span class="nav-text">1.初识 TypeScript</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-TypeScript-%E7%9A%84%E7%89%B9%E7%82%B9"><span class="nav-text">1.1 TypeScript 的特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-%E5%AE%89%E8%A3%85-TypeScript"><span class="nav-text">1.2 安装 TypeScript</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-3-%E7%BC%96%E5%86%99%E7%AC%AC%E4%B8%80%E4%B8%AA-TypeScript-%E7%A8%8B%E5%BA%8F"><span class="nav-text">1.3 编写第一个 TypeScript 程序</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-1-%E7%BC%96%E8%AF%91%E4%BB%A3%E7%A0%81"><span class="nav-text">1.3.1 编译代码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-2-%E7%B1%BB%E5%9E%8B%E6%B3%A8%E8%A7%A3"><span class="nav-text">1.3.2 类型注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-3-%E6%8E%A5%E5%8F%A3"><span class="nav-text">1.3.3 接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-4-%E7%B1%BB"><span class="nav-text">1.3.4 类</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-TypeScript%E5%9F%BA%E7%A1%80%E7%B1%BB%E5%9E%8B"><span class="nav-text">2.TypeScript基础类型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-%E5%B8%83%E5%B0%94%E5%80%BC"><span class="nav-text">2.1 布尔值</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-%E6%95%B0%E5%AD%97"><span class="nav-text">2.2 数字</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-text">2.3 字符串</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-4-%E6%95%B0%E7%BB%84"><span class="nav-text">2.4 数组</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-5-%E5%85%83%E7%A5%96-Tuple"><span class="nav-text">2.5 元祖 Tuple</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-6-%E6%9E%9A%E4%B8%BE"><span class="nav-text">2.6 枚举</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-7-any"><span class="nav-text">2.7 any</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-8-void"><span class="nav-text">2.8 void</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-9-null-%E5%92%8C-undefined"><span class="nav-text">2.9 null 和 undefined</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-10-never"><span class="nav-text">2.10 never</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-11-object"><span class="nav-text">2.11 object</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-12-%E7%B1%BB%E5%9E%8B%E6%96%AD%E8%A8%80"><span class="nav-text">2.12 类型断言</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-%E6%8E%A5%E5%8F%A3"><span class="nav-text">3.接口</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-%E6%8E%A5%E5%8F%A3%E7%9A%84%E5%AE%9A%E4%B9%89"><span class="nav-text">3.1 接口的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-%E5%8F%AF%E9%80%89%E5%B1%9E%E6%80%A7"><span class="nav-text">3.2 可选属性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-%E5%8F%AA%E8%AF%BB%E5%B1%9E%E6%80%A7"><span class="nav-text">3.3 只读属性</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#readonly-%E5%92%8C-const%E5%8C%BA%E5%88%AB"><span class="nav-text">readonly 和 const区别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-4-%E9%A2%9D%E5%A4%96%E7%9A%84%E5%B1%9E%E6%80%A7%E6%A3%80%E6%9F%A5"><span class="nav-text">3.4 额外的属性检查</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-5-%E5%87%BD%E6%95%B0%E7%B1%BB%E5%9E%8B"><span class="nav-text">3.5 函数类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-6-%E5%8F%AF%E7%B4%A2%E5%BC%95%E7%9A%84%E7%B1%BB%E5%9E%8B"><span class="nav-text">3.6 可索引的类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-7-%E7%B1%BB%E7%B1%BB%E5%9E%8B"><span class="nav-text">3.7 类类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-7-1-%E5%AE%9E%E7%8E%B0%E6%8E%A5%E5%8F%A3"><span class="nav-text">3.7.1 实现接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-7-2-%E7%B1%BB%E9%9D%99%E6%80%81%E9%83%A8%E5%88%86%E4%B8%8E%E5%AE%9E%E4%BE%8B%E9%83%A8%E5%88%86%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-text">3.7.2 类静态部分与实例部分的区别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-8-%E7%BB%A7%E6%89%BF%E6%8E%A5%E5%8F%A3"><span class="nav-text">3.8 继承接口</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-9-%E6%B7%B7%E5%90%88%E7%B1%BB%E5%9E%8B"><span class="nav-text">3.9 混合类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-10-%E6%8E%A5%E5%8F%A3%E7%BB%A7%E6%89%BF%E7%B1%BB"><span class="nav-text">3.10 接口继承类</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-%E7%B1%BB"><span class="nav-text">4.类</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-%E7%B1%BB%E7%9A%84%E5%9F%BA%E6%9C%AC%E7%A4%BA%E4%BE%8B"><span class="nav-text">4.1 类的基本示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-%E7%BB%A7%E6%89%BF"><span class="nav-text">4.2 继承</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-%E5%85%AC%E5%85%B1%EF%BC%8C%E7%A7%81%E6%9C%89%E4%B8%8E%E5%8F%97%E4%BF%9D%E6%8A%A4%E7%9A%84%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="nav-text">4.3 公共，私有与受保护的修饰符</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-1-%E9%BB%98%E8%AE%A4public"><span class="nav-text">4.3.1 默认public</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-2-%E7%90%86%E8%A7%A3-private"><span class="nav-text">4.3.2 理解 private</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-3-%E7%90%86%E8%A7%A3-protected"><span class="nav-text">4.3.3 理解 protected</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-4-readonly-%E4%BF%AE%E9%A5%B0%E7%AC%A6"><span class="nav-text">4.4 readonly 修饰符</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-4-1-%E5%8F%82%E6%95%B0%E5%B1%9E%E6%80%A7"><span class="nav-text">4.4.1 参数属性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-5-%E5%AD%98%E5%8F%96%E5%99%A8"><span class="nav-text">4.5 存取器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-6-%E9%9D%99%E6%80%81%E5%B1%9E%E6%80%A7"><span class="nav-text">4.6 静态属性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-7-%E6%8A%BD%E8%B1%A1%E7%B1%BB"><span class="nav-text">4.7 抽象类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-8-%E9%AB%98%E7%BA%A7%E6%8A%80%E5%B7%A7"><span class="nav-text">4.8 高级技巧</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-8-1-%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="nav-text">4.8.1 构造函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-8-2-%E6%8A%8A%E7%B1%BB%E5%BD%93%E5%81%9A%E6%8E%A5%E5%8F%A3%E4%BD%BF%E7%94%A8"><span class="nav-text">4.8.2 把类当做接口使用</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-%E5%87%BD%E6%95%B0"><span class="nav-text">5.函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1-%E5%9F%BA%E6%9C%AC%E7%A4%BA%E4%BE%8B"><span class="nav-text">5.1 基本示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-2-%E5%87%BD%E6%95%B0%E7%B1%BB%E5%9E%8B"><span class="nav-text">5.2 函数类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-1-%E4%B8%BA%E5%87%BD%E6%95%B0%E5%AE%9A%E4%B9%89%E7%B1%BB%E5%9E%8B"><span class="nav-text">5.2.1 为函数定义类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-2-%E4%B9%A6%E5%86%99%E5%AE%8C%E6%95%B4%E5%87%BD%E6%95%B0%E7%B1%BB%E5%9E%8B"><span class="nav-text">5.2.2 书写完整函数类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2-3-%E6%8E%A8%E6%96%AD%E7%B1%BB%E5%9E%8B"><span class="nav-text">5.2.3 推断类型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-3-%E5%8F%AF%E9%80%89%E5%8F%82%E6%95%B0%E5%92%8C%E9%BB%98%E8%AE%A4%E5%8F%82%E6%95%B0"><span class="nav-text">5.3 可选参数和默认参数</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-1-%E5%89%A9%E4%BD%99%E5%8F%82%E6%95%B0"><span class="nav-text">5.3.1 剩余参数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-4-this"><span class="nav-text">5.4 this</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-4-1-this-%E5%92%8C%E7%AE%AD%E5%A4%B4%E5%87%BD%E6%95%B0"><span class="nav-text">5.4.1 this 和箭头函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-4-2-this-%E5%8F%82%E6%95%B0"><span class="nav-text">5.4.2 this 参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-4-3-this-%E5%8F%82%E6%95%B0%E5%9C%A8%E5%9B%9E%E8%B0%83%E5%87%BD%E6%95%B0%E9%87%8C"><span class="nav-text">5.4.3 this 参数在回调函数里</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-5-%E9%87%8D%E8%BD%BD"><span class="nav-text">5.5 重载</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#6-%E6%B3%9B%E5%9E%8B"><span class="nav-text">6.泛型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#6-1-%E6%B3%9B%E5%9E%8B%E5%9F%BA%E7%A1%80%E7%A4%BA%E4%BE%8B"><span class="nav-text">6.1 泛型基础示例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-2-%E4%BD%BF%E7%94%A8%E6%B3%9B%E5%9E%8B%E5%8F%98%E9%87%8F"><span class="nav-text">6.2 使用泛型变量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-3-%E6%B3%9B%E5%9E%8B%E7%B1%BB%E5%9E%8B"><span class="nav-text">6.3 泛型类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-4-%E6%B3%9B%E5%9E%8B%E7%B1%BB"><span class="nav-text">6.4 泛型类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-5-%E6%B3%9B%E5%9E%8B%E7%BA%A6%E6%9D%9F"><span class="nav-text">6.5 泛型约束</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-5-1-%E5%9C%A8%E6%B3%9B%E5%9E%8B%E7%BA%A6%E6%9D%9F%E4%B8%AD%E4%BD%BF%E7%94%A8%E7%B1%BB%E5%9E%8B%E5%8F%82%E6%95%B0"><span class="nav-text">6.5.1 在泛型约束中使用类型参数</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#7-%E7%B1%BB%E5%9E%8B%E6%8E%A8%E6%96%AD"><span class="nav-text">7.类型推断</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#7-1-%E7%B1%BB%E5%9E%8B%E6%8E%A8%E6%96%AD%E5%9F%BA%E7%A1%80"><span class="nav-text">7.1 类型推断基础</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-2-%E6%9C%80%E4%BD%B3%E9%80%9A%E7%94%A8%E7%B1%BB%E5%9E%8B"><span class="nav-text">7.2 最佳通用类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-3-%E4%B8%8A%E4%B8%8B%E6%96%87%E7%B1%BB%E5%9E%8B"><span class="nav-text">7.3 上下文类型</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#8-%E9%AB%98%E7%BA%A7%E7%B1%BB%E5%9E%8B"><span class="nav-text">8.高级类型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#8-1-%E4%BA%A4%E5%8F%89%E7%B1%BB%E5%9E%8B"><span class="nav-text">8.1 交叉类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-2-%E8%81%94%E5%90%88%E7%B1%BB%E5%9E%8B"><span class="nav-text">8.2 联合类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-3-%E7%B1%BB%E5%9E%8B%E4%BF%9D%E6%8A%A4"><span class="nav-text">8.3 类型保护</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#8-3-1-%E7%94%A8%E6%88%B7%E8%87%AA%E5%AE%9A%E4%B9%89%E7%9A%84%E7%B1%BB%E5%9E%8B%E4%BF%9D%E6%8A%A4"><span class="nav-text">8.3.1 用户自定义的类型保护</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#8-3-2-typeof-%E7%B1%BB%E5%9E%8B%E4%BF%9D%E6%8A%A4"><span class="nav-text">8.3.2 typeof 类型保护</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#8-3-3-instanceof-%E7%B1%BB%E5%9E%8B%E4%BF%9D%E6%8A%A4"><span class="nav-text">8.3.3 instanceof 类型保护</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-4-%E5%8F%AF%E4%BB%A5%E4%B8%BA-null-%E7%9A%84%E7%B1%BB%E5%9E%8B"><span class="nav-text">8.4 可以为 null 的类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#8-4-1-%E5%8F%AF%E9%80%89%E5%8F%82%E6%95%B0%E5%92%8C%E5%8F%AF%E9%80%89%E5%B1%9E%E6%80%A7"><span class="nav-text">8.4.1 可选参数和可选属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#8-4-2-%E7%B1%BB%E5%9E%8B%E4%BF%9D%E6%8A%A4%E5%92%8C%E7%B1%BB%E5%9E%8B%E6%96%AD%E8%A8%80"><span class="nav-text">8.4.2 类型保护和类型断言</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-5-%E5%AD%97%E7%AC%A6%E4%B8%B2%E5%AD%97%E9%9D%A2%E9%87%8F%E7%B1%BB%E5%9E%8B"><span class="nav-text">8.5 字符串字面量类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-6-%E6%80%BB%E7%BB%93"><span class="nav-text">8.6 总结</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hxy"
      src="/images/Robben.gif">
  <p class="site-author-name" itemprop="name">hxy</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">80</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">120</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/huxingyi1997" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;huxingyi1997" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huxingyi1997@zju.edu.cn" title="E-Mail → mailto:huxingyi1997@zju.edu.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-frog"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hxy</span>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共1039.2k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'pQsO3ySbU4VtWN2j1FLA74Ha-gzGzoHsz',
      appKey     : 'QYacMDY2VY7Wazprg1X6FiUv',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

  
  <!-- 动态背景特效 -->
  <!-- 樱花特效 -->
    <script async src="/js/src/sakura.js"></script>
    <script async src="/js/src/fairyDustCursor.js"></script>
</body>
</html>
